Introducing a new way to review your PRs.

Read the announcement

reflex-dev / xy

Ultra-fast and customizable Python charts

View on GitHub

20 documents · Updated Nov 18, 2026

docs / native-rendering-primitives

Native rendering primitives

Native rendering primitives are the Rust and Python facilities that turn a chart scene into fast static pixels or vector output. They share screen-space layout and style rules with the live chart, while adding compact data paths for raster marks, text, density surfaces, multi-resolution tiles, and transition identity.

Rendering role

The native facilities sit after chart layout and data preparation. Python selects the visible scene and its display size, then native code paints or serializes that scene without requiring a browser for static output.

This page is a child of the Rust acceleration engine. The related native kernels and Python bindings page covers the data and compute kernels that prepare inputs for these rendering facilities.

The main flow keeps geometry and style decisions in one shared chart model, then sends only the work needed by the selected output surface.

flowchart LR
    A[Chart scene and data] --> B[Shared layout, scales, ticks, and styles]
    B --> C[Screen-space scene commands]
    C --> D[Native raster painter]
    C --> E[SVG serializer]
    A --> F[Tile pyramid for repeated views]
    F --> C
    G[Scalar identity keys] --> H[Stable transitions]
    D --> I[RGBA image or PNG]
    E --> J[SVG document]

Shared scene contract

The native paths use a common screen-space view of the chart. The Python raster writer reuses layout, scale, tick, and color-map logic from the SVG path, so a mark has the same position and broad style meaning across live, SVG, and PNG surfaces. The Rust boundary accepts caller-owned buffers and reports failure with status values rather than allowing a native panic to cross into Python.

References: python/…/_raster.py• L1-10 python/…/_raster.py• L925-948 src/lib.rs• L1-19 src/lib.rs• L41-52

Native output surfaces

The native surface set serves two different needs. Raster output gives a browser-free image for reports and static files, while SVG output keeps chart geometry as a portable vector document. CSS validation, font support, tile reuse, and transition identity support both the visual result and the cost of producing it.

SurfacePrimary resultMain use
Native rasterRGBA pixels or PNG bytesHigh-throughput static image export
Native SVGSVG path and document contentResolution-independent vector export
CSS and font facilitiesSafe style values and stable text paintCross-surface style and text behavior
Tile facilitiesWindow-sized count or color gridsFast repeated views of large point sets
Transition identityUnique stable row keysConsistent matching of animated data

References: src/lib.rs• L168-200 src/lib.rs• L1862-2011 src/lib.rs• L3025-3247

Raster output

The native raster path paints a chart into an RGBA8 image and can encode the image as PNG in the same native call. It is designed for high mark counts by using compact commands, batched arrays, borrowed data spans, and work that is bounded by the output size rather than by every source row.

Raster mark primitives

The raster painter covers the visual parts needed by chart scenes. It supports filled shapes, gradients, strokes, points and symbols, line segments, rectangles, triangles, images, density and heatmap images, and text. A rectangular clip limits ordinary plot marks, and polar marks can use a shared annular-sector clip so the whole mark set respects a polar hole or partial sector.

These primitives give Python one small vocabulary for many chart families. Lines, areas, bars, scatter marks, mesh cells, annotations, axes, legends, and color bars all become ordered paint commands before the native painter runs.

References: src/raster.rs• L1-12 src/raster.rs• L17-35 src/raster.rs• L40-53 python/…/_raster.py• L1063-1107

Raster throughput paths

The raster API separates commands from large read-only data spans. This lets static export borrow existing arrays instead of copying them into the command stream. Large point, segment, stroke, and image work can use disjoint row bands, which allows parallel painting without locks while preserving mark order inside each band.

The API also has a fused raster-and-PNG path. It writes the native framebuffer directly into the PNG encoder, so callers that need PNG bytes do not need a second full-frame conversion step.

API capabilityThroughput goal
Batched points and segmentsReduce per-mark transport and call cost
Borrowed one or more data spansKeep large columns and grids out of command copies
Row-band paintingUse several cores for large pixel workloads
Fused PNG encodingAvoid a separate image handoff and full-frame copy
Density and heatmap pathsPaint compact grids instead of expanding every source point

References: python/…/_raster.py• L191-345 python/…/_raster.py• L1597-1607 src/raster.rs• L2109-2143 src/raster.rs• L2509-2523 src/raster.rs• L3083-3160

Raster style fidelity

Raster style handling resolves the colors that a browser would otherwise compute. Common CSS colors are converted to RGBA values, gradients use native color stops, and unsupported browser-only color expressions use the static export fallback instead of producing an invisible mark. The raster path keeps the shared line-cap, opacity, symbol, and text emphasis rules that define the chart style contract.

Static raster text supports the bundled face's regular, bold, and italic forms. Vector output can preserve a wider CSS text surface, so properties such as font family and letter spacing can differ from the raster surface when a chart asks for them.

References: python/…/_raster.py• L142-176 python/…/_svg.py• L1331-1356 python/…/_raster.py• L1660-1668

SVG output

The SVG facilities produce resolution-independent chart content from the same screen-space scene used by raster export. Their main high-throughput benefit is to serialize dense coordinate arrays without creating one Python string object per point.

SVG geometry serialization

The native SVG helper turns parallel finite coordinate arrays into compact move-and-line path data. It rejects mismatched, empty, or non-finite input so invalid geometry does not become a misleading document.

The broader SVG writer still owns document structure, layout, styles, text, gradients, and chart-specific elements. The native helper accelerates the high-cardinality coordinate part while preserving the writer's number format.

References: src/svg.rs• L1-42 src/lib.rs• L168-200 python/…/_svg.py• L1-16

SVG and raster parity

SVG and raster export share layout, scales, tick rules, colormaps, and mark styling. Curves that need a native raster primitive are flattened into screen-space geometry before painting, while SVG can keep suitable geometry in vector form. Browser-only CSS expressions remain browser-dependent in SVG but receive a stable static fallback in PNG.

This split keeps each output surface useful without making the native raster painter emulate a full browser CSS engine. The shared scene decisions are the important contract; the final encoding can differ.

References: python/…/_svg.py• L1-16 python/…/_raster.py• L1-10 python/…/_raster.py• L807-813 python/…/_raster.py• L1632-1657

Styling and text

CSS and font facilities make native output safe and readable while keeping style choices aligned with the browser client. CSS values are checked at the native boundary, and raster text uses a bundled glyph resource rather than a run-time font service.

CSS value contract

The CSS validator uses a tiered contract. Closed forms such as hex, RGB, HSL, lengths, and numbers are checked strictly; valid browser-only forms such as custom-property references and newer color functions pass through for browser resolution. Every declaration also receives a safety check that prevents a value from escaping its declaration or style container.

The same native grammar serves Python's style gate and raster color resolution. This keeps invalid colors loud and prevents the API, static export, and browser export from silently choosing different meanings.

References: src/css.rs• L1-21 src/css.rs• L39-67 src/css.rs• L315-352 src/css.rs• L451-499 src/css.rs• L598-649 src/lib.rs• L387-404

Bundled font rendering

Native raster text uses a generated grayscale glyph atlas with glyph metrics and coverage values. The raster painter scales and blends those glyphs at paint time, which removes the need for a run-time font library in the static PNG path.

The atlas supports the chart's common text and symbol range and carries the regular face plus the emphasis data needed for bold and italic text. The vector path uses CSS text properties more broadly, so the two surfaces share visual intent but do not promise identical font selection for every CSS property.

References: src/font.rs• L1-21 python/…/_raster.py• L1440-1503 python/…/_raster.py• L1505-1536 python/…/_svg.py• L1331-1356

Multi-resolution tile surfaces

Tile facilities turn a large point set into a reusable multi-resolution count surface. A tile pyramid is built once for a trace's full data bounds, then supplies a small grid for each visible window so interaction does not need to scan all source points again.

Count and color pyramids

Each pyramid level represents the same domain at a different grid size. Higher levels combine four neighboring cells into one and preserve the total count. A colored pyramid adds a mean-color plane so density views can retain the average point color as they zoom out.

The compose operation chooses the coarsest level that can meet the requested render size. It area-weights cells when reducing resolution and fills blocks when increasing resolution. If the finest level cannot resolve the window within the allowed upsample limit, the API refuses the request so the caller can use an exact re-bin instead of showing an overly blurred result.

References: src/tiles.rs• L1-21 src/tiles.rs• L28-43 src/tiles.rs• L59-172 src/tiles.rs• L315-352 src/tiles.rs• L354-477 src/tiles.rs• L577-719

Tile lifecycle

The C API exposes a tile pyramid as an opaque handle. Callers can build a count or colored pyramid, compose a window, count points in a window, append points that remain inside the original domain, and release the handle. A colored pyramid does not accept an uncolored append because that could change its color or domain meaning; the caller must invalidate it and rebuild it when needed.

The registry drops its lock before a count or compose operation runs. This lets independent views compute at the same time and makes a stale or busy handle an ordinary failure that can trigger lazy rebuild.

References: src/tiles.rs• L175-217 src/tiles.rs• L721-765 src/lib.rs• L3025-3247

Transition identity

Transition identity gives animated chart rows a stable key across updates. The native encoder reads homogeneous fixed-width scalar data and produces the same type-qualified keys as the Python API without creating one Python object per row.

Stable scalar keys

The key facility accepts fixed-width Unicode, byte strings, booleans, signed integers, unsigned integers, and float64 values. It normalizes each supported scalar to the public key form, rejects invalid scalar layouts and non-finite float values, and checks that the result is unique.

The C API reports invalid data, duplicate values, and digest collisions as separate outcomes. This distinction lets the transition layer reject a bad identity set instead of animating unrelated rows as if they were the same row.

References: src/transition.rs• L1-23 src/transition.rs• L391-495 src/lib.rs• L94-165

Change checklist

When these files or sections are changed, remember to consider these:

  • Keep the Python command writer and Rust command reader aligned when a raster primitive or its data span changes. A command change can also require an ABI version change in src/lib.rs.
  • Keep SVG and raster scene choices aligned when layout, scales, ticks, colormaps, polar geometry, or mark styling changes. Both static paths must continue to describe the same chart.
  • Keep CSS validation and raster color resolution aligned when a value grammar changes. Browser-only values must retain their pass-through or static-fallback behavior.
  • Regenerate the font atlas and preserve its metrics when the source face or supported glyph set changes. Text placement depends on those metrics.
  • Keep count and mean-color composition on the same tile level and preserve the refusal contract for windows that exceed the pyramid's resolution.
  • Preserve the Python transition-key token rules and the distinct duplicate versus collision statuses when scalar kinds or byte layouts change.

Important failure modes

TriggerConsequenceGuard
Malformed raster commands or an output-size mismatchRaster calls return failure and the output is undefinedValidate command data and w*h*4 before treating the buffer as an image
Non-finite or mismatched SVG coordinatesNo SVG path is producedKeep coordinate arrays parallel, non-empty, and finite
Unsafe or malformed CSS textThe style value is rejected instead of being serializedUse the CSS declaration and value checks before export
Browser-only color in a static raster exportThe exact browser color is unavailable and the native fallback is usedUse the documented static fallback or choose SVG/browser output when exact browser resolution is required
Tile window exceeds the pyramid's allowed resolutionComposition returns refusal and no trustworthy high-detail grid is availableHandle the refusal with an exact re-bin and disclose the fallback
Stale, busy, or colored-pyramid append handleThe update is not appliedInvalidate and rebuild the pyramid when the handle cannot accept the update
Duplicate transition keys or a digest collisionRow matching is rejected rather than producing an unsafe animationTreat the reported key error as a transition-input failure

Key files

FileWhy to read it
python/…/_raster.pyShows how a shared chart scene becomes native paint commands and how static output selects borrowed data and PNG paths
src/raster.rsDefines the native paint contract for shapes, images, text, clipping, batching, and PNG output
python/…/_svg.pyDefines shared static layout and SVG export behavior used to keep vector and raster results aligned
src/svg.rsProvides the focused native path serializer for dense screen-space geometry
src/css.rsDefines the safe CSS value and color contract shared by API validation and native raster color handling
src/font.rsHolds the generated glyph metrics and coverage resource used by native raster text
src/tiles.rsDefines reusable count and color pyramids plus window composition and handle lifecycle
src/transition.rsDefines stable scalar identity encoding and duplicate or collision detection for transitions
src/lib.rsExposes the native facilities through the versioned C ABI and documents their success and failure outcomes