vector
Garnet vector
require "garnet-vector" supplies immutable local-coordinate paths and fill/stroke primitives with solid, gradient or image-pattern paints. It depends only on generic graphics; no window, renderer, ECS, or native library is initialized or required.
require "garnet-vector"
alias V = Garnet::Vector
path = V::Path.build do |p|
p.move_to(10, 10)
p.curve_to(40, 0, 70, 100, 100, 40)
end
drawing = Garnet::Graphics::Drawing.record do |canvas|
canvas.save do
canvas.translate(20_f32, 20_f32)
canvas.stroke(path, paint: Garnet::Color::WHITE,
style: V::Stroke.new(width: 4.0, cap: :round, join: :round))
end
end
texture = renderer.render(drawing, Garnet::Graphics::RenderTarget.new(320, 240))
Path.build / Builder#finish copy commands; retained builders cannot modify published paths. Curves remain curves until geometry preparation. move_to, line_to, quadratic_to, curve_to, arc, arc_to, ellipse, svg_arc_to, close, rect, circle, and round_rect are supported. Circle and rounded-rectangle helpers retain analytic circular arcs. Shape implements the shared Graphics::Primitive contract. StrokedShape does the same for stroke outlines. Use either in a scene Graphics::Components::Drawable.
fill(path, paint:, rule:), stroke(path, paint:, style:), and scoped clip(path) { ... } extend the shared recorder. Fill rules are nonzero/even-odd. Stroke caps are butt/round/square; joins are miter/round/bevel with a miter limit. Dash sequences are copied, support offsets and odd-length repetition, and accept nonnegative entries. Zero on-dashes produce round or tangent-oriented square dots (butt caps produce no dot); all-zero patterns behave as solid strokes. Zero gaps preserve connected joins. Overlapping stroke pieces are filled as a union before alpha blending.
The first compiler is a bounded Crystal scanbeam tessellator: flatten curves, split bands at edge intersections, apply winding, triangulate the resulting disjoint trapezoids. It handles holes and self-intersections. Geometry tolerance is chosen from the draw transform and target pixel scale. Rendering uses 2× supersampling per axis by default, resolving premultiplied color on GPU; samples: 1 disables it. No CPU rasterization or readback is used for drawing, masks, or composition.
Shape#paint, recorder fills, and strokes accept a Garnet::Color or a shared graphics LinearGradient, RadialGradient or ImagePattern. Paints use geometry-local coordinates, including for stroke outlines, and follow the scene transform. See the gradient API and image-pattern API for coordinate mapping, interpolation and backend limits. Image patterns can also reuse an explicitly captured scene texture on the GPU.
Use shared Recorder#draw_pattern to paint a shape or stroke from another mixed drawing, or the scene Pattern component for a live viewport source. These lower through the same image-pattern material. Tile resolution remains explicit; drawing-backed patterns describe the API.
This is an initial paint profile, not SVG/Lottie format support. Glyph/font services, and format evaluators remain later work. The tessellator checks a 4096-edge limit and has quadratic intersection work; it is not the final high-complexity geometry engine. No persistent tessellation cache is implemented yet. Extremely large coordinates and nearly coincident geometry need further robustness work before claiming unrestricted format conformance.
Run scripts/check-composition unit from the workspace, or install dependencies and run crystal spec from this shard. The mixed gallery uses the same scene on GL, Metal, and Vulkan.
The optional garnet-svg shard parses SVG path-data strings into these same paths. Vector geometry remains independent of SVG syntax, document parsing, and styling.
Elliptical arcs
arc(cx, cy, radius, start_angle, end_angle, counterclockwise: false) and ellipse(cx, cy, rx, ry, rotation, start_angle, end_angle, counterclockwise: false) use radians. They connect the current point to the start of the arc, or start a subpath when none exists. Positive angles sweep clockwise in top-left coordinates. Sweeps are limited to one revolution; a full turn needs an explicit close to close the subpath. This follows the Canvas ellipse geometry rules, with Garnet raising ArgumentError for nonfinite inputs instead of silently ignoring them. Negative radii are rejected; zero radii are allowed.
path = V::Path.build do |p|
p.ellipse(100, 80, 60, 25, Math::PI/6, 0, 2*Math::PI)
p.close
p.move_to(20, 120)
p.svg_arc_to(40, 15, 30, false, true, 100, 120)
end
svg_arc_to(rx, ry, rotation_degrees, large_arc, sweep, x, y) requires a current point and uses an absolute endpoint. Its rotation is in degrees, matching the SVG path command. It applies the SVG endpoint conversion and radii correction: negative radii become positive, insufficient radii are scaled, a zero radius becomes a line, and identical endpoints add nothing. Boolean flags select the large/small arc and sweep direction. This is a geometry operation; it does not parse SVG path strings or documents.
Arcs stay analytic in the immutable path. Geometry preparation chooses angular segments using the bound max(rx, ry) * step² / 8 <= tolerance, with steps no larger than a quarter turn. Exact supplied SVG endpoints are retained. The existing subdivision/edge budgets apply; excessive resolution demands and unsupported numeric ranges raise explicitly. Filled arcs, dashed strokes, clips, gradients, and image/scene patterns all use the same preparation path.
Path#bounds(transform = Mat4.identity) returns geometry-local {min_x, min_y, max_x, max_y} as Float64 values, or nil for an empty path. It includes analytic cubic and elliptical extrema after the supplied finite affine transform, excludes isolated moves and stroke expansion, and is independent of tessellation tolerance. Transforming the curve itself avoids the loose bounds obtained by rotating an already-computed bounding rectangle. This supports object-relative paints without retaining tessellated geometry.
Measuring and trimming paths
measurement = path.measure(tolerance: 0.01, max_segments: 65_536)
length = measurement.length
sample = measurement.sample(length * 0.5) # PathSample? with point and unit tangent
partial = measurement.trim(length * 0.2, length * 0.8)
recorder.stroke(partial, Garnet::Color::WHITE, V::Stroke.new(width: 2.0))
Retain the immutable PathMeasure to reuse its distance tables. Measurements use local path units and concatenate contour distances without charging for moves. contours returns a copied array of immutable ContourMeasure objects, each exposing length, closed?, sample and trim. Zero-length contours/edges are omitted by Path#measure; empty measurements have length zero and return nil from sample.
Sampling clamps finite distances to the measured range. At an interior vertex it uses the outgoing edge tangent; at a contour boundary it chooses the next nonempty contour, and at the final endpoint it uses the incoming tangent. There is no unique smooth tangent at a corner. Distance lookup within a contour uses binary search.
Trimming takes two finite, ordered, absolute distances and clamps them to the measured range. Equal endpoints produce an empty path. Separate contours remain separate; a fully included closed contour stays closed, while partial contours are open. Wrapping, reverse traversal and fractional ranges are not implicit: callers can scale fractions by length or compose separate intervals explicitly.
Distance tables approximate cubic and elliptical arc length with parameter-aware subdivision. Circular arc lengths are exact. Samples evaluate the analytic curve and its derivative; at stationary points the table chord supplies a fallback tangent. Trims retain cubic and elliptical arc commands, using de Casteljau subdivision for cubics. Their cut parameters still depend on the approximate distance table. tolerance controls geometric subdivision, not total accumulated arc-length error. Segment/depth limits apply; nonfinite and unrepresentable distance increments raise. Globally bounded arc-length integration remains future work.
Editing geometry
Path#reverse reverses each contour while preserving contour order and closure. Path#morph(other, amount) creates a new path with corresponding points interpolated at a finite amount within 0..1. Matching command counts and kinds are required; elliptical commands additionally require matching rotation and angular sweeps. This is explicit topology correspondence, not automatic shape matching. commands returns a copied array.
Builder#arc_to(x1, y1, x2, y2, radius) connects the current point to a circular arc tangent to the two lines through the corner (x1, y1). With no current point it moves to the corner; coincident/collinear points and zero radius produce a line. Negative/nonfinite radii raise. Tangency may extend beyond the finite line segments.
The optional Clipper adapter supplies polygon Boolean operations, offsets, and native triangulation without introducing a dependency into this shard.
Non-scaling strokes
Stroke.new(width: 4.0, non_scaling: true) keeps widths and dash lengths in output pixels under affine scene transforms, including nonuniform scale, rotation and shear. The planner supplies a local-to-output-pixel transform; stroke expansion runs in that space and returns ordinary local-coordinate mesh vertices, preserving local gradient/pattern coordinates. Coverage and drawing-pattern wrappers forward this preparation context. Singular transforms produce no geometry; perspective transforms are explicitly unsupported for this stroke mode. Direct Stroke#outline still operates in the coordinate space of the path supplied to it. No renderer-specific stroke implementation is required.
vector
- 0
- 0
- 0
- 7
- 1
- 1 day ago
- November 30, 2026
MIT License
Wed, 02 Dec 2026 02:09:01 GMT