Two-dimensional drawing for MoonBit: paths, fill and stroke tessellation, glyph atlas and a software rasteriser.
moon add moonbitstack/moongfx| Package | What it holds |
|---|---|
| moonbitstack/moongfx | Paths, tessellation, paints, masks, clipping, the glyph atlas, and the Canvas and Backend contracts |
| moonbitstack/moongfx/soft | The software backend: an RGBA frame buffer with antialiasing, gradients, images and clips |
| moonbitstack/moongfx/gpu | The batch format a GPU backend uploads: vertices, index ranges, draw calls, textures |
let surface = @soft.Surface::new(120, 80)
let canvas = @moongfx.Canvas::new(surface)
canvas.clear(@moonrgba.Color::rgb(250, 248, 244))
canvas.fill_circle(
@moonmath.Vec2::new(60.0, 40.0),
28.0,
@moongfx.solid(@moonrgba.Color::rgb(226, 88, 74)),
)
let (r, g, b, a) = surface.pixel(60, 40)
assert_eq(r > 0.8, true)
assert_eq(a > 0.99, true)let badge = @moongfx.Path::builder()
.rounded_rect(
{ min_x: 8.0, min_y: 8.0, max_x: 108.0, max_y: 64.0 },
@moongfx.Corners::same(12.0),
)
.build()
let curve = @moongfx.Path::builder()
.move_to(@moonmath.Vec2::new(0.0, 40.0))
.quad_to(@moonmath.Vec2::new(30.0, 0.0), @moonmath.Vec2::new(60.0, 40.0))
.cubic_to(
@moonmath.Vec2::new(75.0, 60.0),
@moonmath.Vec2::new(90.0, 20.0),
@moonmath.Vec2::new(110.0, 40.0),
)
.build()
assert_eq(badge.is_empty(), false)
assert_eq(curve.bounds().width() > 100.0, true)let quarter = @moongfx.Path::builder()
.move_to(@moonmath.Vec2::new(10.0, 0.0))
.arc_to(10.0, 10.0, 0.0, false, true, @moonmath.Vec2::new(0.0, 10.0))
.build()
assert_eq(quarter.bounds().max_x <= 10.001, true)let circle = @moongfx.Path::builder()
.circle(@moonmath.Vec2::new(0.0, 0.0), 100.0)
.build()
let coarse = circle.flatten(flatten=@moongfx.coarse)
let fine = circle.flatten(flatten=@moongfx.fine)
assert_eq(fine[0].points().length() > coarse[0].points().length(), true)let star = @moongfx.Path::builder()
.move_to(@moonmath.Vec2::new(60.0, 10.0))
.line_to(@moonmath.Vec2::new(95.0, 120.0))
.line_to(@moonmath.Vec2::new(5.0, 50.0))
.line_to(@moonmath.Vec2::new(115.0, 50.0))
.line_to(@moonmath.Vec2::new(25.0, 120.0))
.close()
.build()
let filled = @moongfx.fill(star)
let holed = @moongfx.fill(star, rule=@moongfx.EvenOdd)
assert_eq(filled.length() > 0, true)
assert_eq(holed.length() < filled.length(), true)let ring = @moongfx.Path::builder()
.circle(@moonmath.Vec2::new(50.0, 50.0), 40.0)
.move_to(@moonmath.Vec2::new(70.0, 50.0))
.arc(@moonmath.Vec2::new(50.0, 50.0), 20.0, 0.0, -6.283185307179586)
.close()
.build()
let triangles = @moongfx.fill(ring)
let mut area : Double = 0.0
for triangle in triangles {
area = area + triangle.area().to_double().abs()
}
assert_eq(area > 3000.0 && area < 4000.0, true)let zigzag = @moongfx.Path::builder()
.move_to(@moonmath.Vec2::new(0.0, 0.0))
.line_to(@moonmath.Vec2::new(40.0, -20.0))
.line_to(@moonmath.Vec2::new(80.0, 20.0))
.build()
let rounded = @moongfx.Stroke::new(8.0)
.with_join(@moongfx.Round)
.with_cap(@moongfx.Round)
let outlined = @moongfx.stroke(zigzag, rounded)
assert_eq(outlined.length() > 0, true)| Knob | What it does |
|---|---|
| width | The width of the line, in drawing units |
| join | Miter, Bevel or Round, for the outside of a corner |
| cap | Butt, Square or Round, for the end of an open path |
| miter_limit | How far a miter may reach before it is bevelled instead, as a multiple of the width |
| dash | Lengths alternating on and off, with dash_offset for the phase |
| tolerance | How closely the outline follows a curve |
let dashed = @moongfx.Stroke::new(6.0).with_dashes([12.0, 8.0], offset=4.0)
let dashed_triangles = @moongfx.stroke(zigzag, dashed)
assert_eq(dashed_triangles.length() > 0, true)let ramp = @moongfx.Gradient::new([
{ offset: 0.0, color: @moonrgba.Color::rgb(250, 200, 80) },
{ offset: 0.5, color: @moonrgba.Color::rgb(232, 120, 90) },
{ offset: 1.0, color: @moonrgba.Color::rgb(90, 120, 220) },
])
let sweep = @moongfx.linear(
@moonmath.Vec2::new(0.0, 0.0),
@moonmath.Vec2::new(100.0, 0.0),
ramp,
)
let (red, _, _, _) = sweep.sample(@moonmath.Vec2::new(0.0, 0.0))
assert_eq(red > 0.9, true)let tiled = @moongfx.Gradient::new(
[
{ offset: 0.0, color: @moonrgba.Color::rgb(0, 0, 0) },
{ offset: 1.0, color: @moonrgba.Color::rgb(255, 255, 255) },
],
spread=@moongfx.Repeat,
)
let stripes = @moongfx.linear(
@moonmath.Vec2::new(0.0, 0.0),
@moonmath.Vec2::new(10.0, 0.0),
tiled,
)
let (shade, _, _, _) = stripes.sample(@moonmath.Vec2::new(2.5, 0.0))
assert_eq(shade > 0.2 && shade < 0.3, true)let glow = @moongfx.radial(
@moonmath.Vec2::new(50.0, 50.0),
40.0,
@moongfx.Gradient::two(@moonrgba.Color::rgb(255, 255, 255), @moonrgba.Color::rgb(20, 30, 60)),
)
let (edge, _, _, _) = glow.sample(@moonmath.Vec2::new(90.0, 50.0))
assert_eq(edge < 0.2, true)let bytes : Array[Byte] = [
b'\xFF', b'\x00', b'\x00', b'\xFF',
]
let dot = try {
@moonimage.Image::of(1, 1, @moonimage.PixelFormat::Rgba8, Bytes::from_array(bytes))
} catch {
_ => @moonimage.Image::new(1, 1, @moonimage.PixelFormat::Rgba8)
}
let tile = @moongfx.Texture({
image: dot,
transform: @moonmath.Affine2::from_scale(@moonmath.Vec2::new(8.0, 8.0)),
filter: @moongfx.Nearest,
})
let (r, _, _, _) = tile.sample(@moonmath.Vec2::new(4.0, 4.0))
assert_eq(r > 0.9, true)let surface = @soft.Surface::new(100, 100)
let canvas = @moongfx.Canvas::new(surface)
canvas.save()
canvas.translate(50.0, 50.0)
canvas.rotate(0.5)
canvas.clip(
@moongfx.Path::builder().circle(@moonmath.Vec2::new(0.0, 0.0), 30.0).build(),
)
canvas.fill_rect(
{ min_x: -40.0, min_y: -40.0, max_x: 40.0, max_y: 40.0 },
@moongfx.solid(@moonrgba.Color::rgb(40, 44, 60)),
)
canvas.restore()
let (_, _, _, inside) = surface.pixel(50, 50)
let (_, _, _, outside) = surface.pixel(2, 2)
assert_eq(inside > 0.9, true)
assert_eq(outside, 0.0)let surface = @soft.Surface::new(200, 40)
let canvas = @moongfx.Canvas::new(surface)
let face = @moongfx.DemoFace::new()
let cache = @moongfx.GlyphCache::new(face)
let ink = @moongfx.solid(@moonrgba.Color::rgb(20, 20, 30))
let advance = canvas.fill_text(@moonmath.Vec2::new(8.0, 30.0), "MOON", 24.0, ink, cache)
assert_eq(advance, 72.0)
assert_eq(cache.misses() > 0, true)let builder = @gpu.BatchBuilder::new()
let square = @moongfx.Path::builder()
.rect({ min_x: 0.0, min_y: 0.0, max_x: 16.0, max_y: 16.0 })
.build()
builder.fill(@moongfx.fill(square), @moongfx.solid(@moonrgba.Color::rgb(80, 120, 200)))
let batch = builder.build()
assert_eq(batch.triangle_count(), 2)
assert_eq(batch.draw_count(), 1)
assert_eq(batch.indices.length(), 6)let surface = @soft.Surface::new(8, 8)
let canvas = @moongfx.Canvas::new(surface)
canvas.clear(@moonrgba.Color::rgb(255, 255, 255))
let image = surface.to_image()
assert_eq(image.width.to_int(), 8)
assert_eq(image.format, @moonimage.PixelFormat::Rgba8)| Scene | Mean difference | Worst pixel |
|---|---|---|
| fill | 0.00045 | 0.15 |
| stroke | 0.00105 | 0.69 |
| gradient | 0.00028 | 0.25 |
| text | 0.00000 | 0.00 |
| clip | 0.00014 | 0.20 |
| curves | 0.00067 | 0.29 |
| Type | Where | What it is |
|---|---|---|
| Path | moongfx | A sequence of MoveTo, LineTo, QuadTo, CubicTo, Arc and Close steps |
| PathBuilder | moongfx | Chains the steps and the shape helpers into a Path |
| Arc | moongfx | A circular arc: centre, radius, start angle, sweep |
| Corners | moongfx | Four corner radii, for a rounded rectangle |
| Bounds | moongfx | An axis-aligned box, possibly empty |
| Triangle | moongfx | Three corners; what a backend fills |
| FillRule | moongfx | NonZero or EvenOdd |
| Flatten | moongfx | A flattening tolerance, with coarse, standard and fine presets |
| Stroke | moongfx | Width, join, cap, miter limit, dashes, tolerance |
| Join, Cap | moongfx | The corner and end styles |
| Paint | moongfx | Solid, Linear, Radial or Texture |
| Gradient, Stop, Spread | moongfx | The colours of a ramp and what happens past its ends |
| LinearGradient, RadialGradient | moongfx | Geometry and a ramp |
| ImagePattern, Filter | moongfx | An image, where it lands, how it is resampled |
| Mask | moongfx | Eight-bit coverage: a clip, or a rasterised glyph |
| Quad | moongfx | Four corners in device space |
| Canvas | moongfx | Transform stack, clip stack, and the drawing calls |
| Backend | moongfx | What a rasteriser implements |
| Atlas, Region, Shelf | moongfx | Shelf packing for coverage |
| Glyph, GlyphSource, GlyphCache, GlyphKey, GlyphEntry | moongfx | Rasterised glyphs and the cache that packs them |
| DemoFace | moongfx | A built-in five by seven face |
| Surface | moongfx/soft | The frame buffer, with pixel and to_image |
| Batch, BatchBuilder, DrawCall, Vertex, Texture | moongfx/gpu | What a GPU backend uploads |
| Function | What it does |
|---|---|
| fill(path, rule~, flatten~) | The path as triangles |
| stroke(path, stroke, flatten~) | The stroke as triangles |
| fill_contours(contours, rule) | The same, from polygons you already have |
| rasterize(triangles, width, height) | The triangles as a coverage mask |
| solid, linear, radial | The paints that are not an image |
| measure_text(cache, text, size) | How wide a run will be |
| Canvas::fill, Canvas::stroke_path, Canvas::clip | Draw through a canvas |
| Canvas::fill_text | Draw a run, returning the advance |
pub(open) trait Backend {
fn width(Self) -> Int
fn height(Self) -> Int
fn clear(Self, Color) -> Unit
fn fill_triangles(Self, Array[Triangle], Paint) -> Unit
fn fill_mask(Self, Mask, Bounds, Quad, Paint) -> Unit
fn draw_image(Self, Image, Quad, Float) -> Unit
fn push_clip(Self, Mask) -> Unit
fn pop_clip(Self) -> Unit
fn flush(Self) -> Unit
}pub(open) trait GlyphSource {
fn glyph(Self, code : Char, size : Float) -> Glyph?
fn ascent(Self, size : Float) -> Float
fn descent(Self, size : Float) -> Float
}fn Canvas::fill_text(self : Canvas, at : Vec2, text : StringView, size : Float, paint : Paint, cache : GlyphCache) -> Floatimpl GlyphSource for DemoFacepub struct GlyphCache {
source : &GlyphSource
atlas : Atlas
entries : Map[GlyphKey, GlyphEntry]
clock : Int
hits : Int
misses : Int
resets : Int
}fn GlyphCache::new(source : &GlyphSource, width? : Int, height? : Int, max_height? : Int) -> GlyphCacheimpl Debug for ImagePatternpub(all) enum Paint {
Solid(Color)
Linear(LinearGradient)
Radial(RadialGradient)
Texture(ImagePattern)
}fn PathBuilder::arc(self : PathBuilder, centre : Vec2, radius : Float, start_angle : Float, sweep_angle : Float) -> PathBuilderfn PathBuilder::arc_to(self : PathBuilder, rx : Float, ry : Float, rotation : Float, large_arc : Bool, sweep_flag : Bool, p : Vec2) -> PathBuilderfn PathBuilder::cubic_to(self : PathBuilder, control1 : Vec2, control2 : Vec2, p : Vec2) -> PathBuilderfn PathBuilder::ellipse(self : PathBuilder, centre : Vec2, radius_x : Float, radius_y : Float) -> PathBuilderpub struct Shelf {
y : Int
height : Int
cursor : Int
}Install
Download zipTwo-dimensional drawing for MoonBit: paths, fill and stroke tessellation, glyph atlas and a software rasteriser.