Skip to content

Instantly share code, notes, and snippets.

@lbmn
Created February 24, 2017 08:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lbmn/32f20a60e8cc4b5157c9a94fa3adcafc to your computer and use it in GitHub Desktop.
Save lbmn/32f20a60e8cc4b5157c9a94fa3adcafc to your computer and use it in GitHub Desktop.
import
math, cairo
type point = tuple[x, y: float]
type trian = tuple[head, left, right: point]
type trias = seq[trian]
let
size : float = 2000
border: float = 10
level = 12
image = "nim.png"
var
surface: PSurface
cr: PContext
proc triangle: trian =
let x = size / 2.0 - border
let y = x * 3.float64.sqrt
let v = (size - y) / 2.0
((size / 2.0, v), (border, size - v), (size - border, size - v))
proc fill(left, right, tail: point) =
let
r = ( size - tail.y ) / size
g = ( size - tail.x ) / size
b = tail.x / size
cr.set_source_rgb(r, g, b)
cr.move_to(left.x, left.y)
cr.line_to(right.x, right.y)
cr.line_to(tail.x, tail.y)
cr.fill
proc draw(level: int, ts: trias): trias =
if level == 0: return
let x = (ts[0].head.x - ts[0].left.x) / 2.0
if x < 1.0: return
let y = (ts[0].left.y - ts[0].head.y) / 2.0
var next: trias = newSeq[trian]()
for it in ts:
let (HEAD, LEFT, RIGHT) = it
let left = (HEAD.x - x, HEAD.y + y)
let right = (HEAD.x + x, HEAD.y + y)
let tail = (HEAD.x, LEFT.y)
fill left, right, tail
next.add @[
(HEAD, left, right),
(left, LEFT, tail),
(right, tail, RIGHT)
]
draw( level - 1, next )
proc go =
let SIZE = size.int32
surface = image_surface_create(TFORMAT.FORMAT_ARGB32, SIZE, SIZE)
cr = surface.create
cr.rectangle(0, 0, size, size)
cr.fill
cr.set_line_width 0.5
let t1 = @[triangle()]
discard draw(level, t1)
discard surface.write_to_png image
go()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment