-
Notifications
You must be signed in to change notification settings - Fork 0
/
ivan.go
120 lines (98 loc) · 2.32 KB
/
ivan.go
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
package main
import (
"flag"
"fmt"
"image"
"image/color"
_ "image/jpeg"
"log"
"os"
"strings"
"sync"
"time"
"./blockartlib"
"./crypto"
)
var (
minerAddr = flag.String("miner", "127.0.0.1:8080", "the address of the miner to connect to")
public = flag.String("public", "testkeys/test1-public.key", "public key file")
private = flag.String("private", "testkeys/test1-private.key", "private key file")
img = flag.String("f", "testdata/ivanb.jpg", "the image to render")
)
func main() {
flag.Parse()
log.SetFlags(log.Flags() | log.Lshortfile)
if err := run(); err != nil {
log.Fatal(err)
}
}
func webColor(c color.Color) string {
r, g, b, a := c.RGBA()
const max = 0xffff
return fmt.Sprintf("rgba(%d, %d, %d, %f)", int(float64(r)/max*255), int(float64(g)/max*255), int(float64(b)/max*255), float64(a)/max)
}
func run() error {
privKey, err := crypto.LoadPrivate(*public, *private)
if err != nil {
return err
}
// Open a canvas.
canvas, _, err := blockartlib.OpenCanvas(*minerAddr, *privKey)
if err != nil {
return err
}
reader, err := os.Open(*img)
if err != nil {
return err
}
defer reader.Close()
img, _, err := image.Decode(reader)
if err != nil {
return err
}
bounds := img.Bounds()
margin := 100
const workers = 128
type work struct {
path, fill, stroke string
}
workChan := make(chan work, workers)
var wg sync.WaitGroup
log.Printf("spinning up %d workers", workers)
for i := 0; i < workers; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for w := range workChan {
for {
if _, _, _, err := canvas.AddShape(0, blockartlib.PATH, w.path, w.fill, w.stroke); err != nil {
if strings.HasPrefix(err.Error(), "BlockArt: Not enough ink to addShape") {
log.Printf("%q: sleeping... %s", w.path, err)
time.Sleep(1 * time.Second)
continue
} else {
log.Fatal(err)
}
}
break
}
}
}()
}
const stride = 4
for x := bounds.Min.X; x < bounds.Max.X; x += stride {
for y := bounds.Min.Y; y < bounds.Max.Y; y += stride {
log.Printf("drawing %d x %d", x, y)
color := webColor(img.At(x, y))
path := fmt.Sprintf("M %d %d v %d h %d v -%d Z", margin+x, margin+y, stride, stride, stride)
workChan <- work{
path: path,
fill: color,
stroke: color,
}
}
}
close(workChan)
wg.Wait()
return nil
}