summaryrefslogtreecommitdiff
path: root/tek.go
blob: f94eb3bcf870343aefeba3619763b3c80a349aac (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package main

import (
	"bufio"
	"io"
	"os"
)

const (
	height = 3072
	width  = 4096
)

type Out struct {
	*bufio.Writer
	hix, hiy, lox, loy, eb int
	xterm                  bool
}

func NewOut(w io.Writer) *Out {
	return &Out{
		Writer: bufio.NewWriter(w),
		xterm:  os.Getenv("TERM") == "xterm",
	}
}

func (o Out) Enable() {
	if o.xterm {
		o.WriteByte(0x1b)
		o.WriteString("[?38h")
		o.Flush()
	}
}

func (o Out) Disable() {
	if o.xterm {
		o.WriteByte(0x1b)
		o.WriteByte(0x03)
		o.Flush()
	}
}

func (o Out) Clear() {
	o.Enable()
	o.WriteByte(0x1b)
	o.WriteByte(0x0c)
	o.Disable()
	o.Flush()
}

func (o Out) PenUp() {
	o.WriteByte(0x1d)
	o.WriteByte(0x07)
	o.Flush()
}

func (o Out) PenDown() {
	o.WriteByte(0x1d)
	o.Flush()
}

func limit(val, max int) int {
	if val < 0 {
		return 0
	}
	if val >= max {
		return max - 1
	}
	return val
}

func (o *Out) Plot(x, y int) {
	x = limit(x, width)
	y = limit(y, height)

	hix := (x >> 7) & 0x1f
	hiy := (y >> 7) & 0x1f
	lox := (x >> 2) & 0x1f
	loy := (y >> 2) & 0x1f
	eb := (x & 3) | ((y & 3) << 2)

	if hiy != o.hiy {
		o.WriteByte(byte(hiy | 0x20))
	}
	if eb != o.eb {
		o.WriteByte(byte(eb | 0x60))
	}
	if eb != o.eb || loy != o.loy || hix != o.hix {
		o.WriteByte(byte(loy | 0x60))
	}
	if hix != o.hix {
		o.WriteByte(byte(hix | 0x20))
	}
	o.WriteByte(byte(lox | 0x40))
	o.hix = hix
	o.hiy = hiy
	o.lox = lox
	o.loy = loy
	o.eb = eb
	o.Flush()
}