-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtartanizer.fsx
326 lines (280 loc) · 11.6 KB
/
tartanizer.fsx
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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
#r "System.Drawing.Common.dll"
open System
module Int =
let tryParse(s : string) =
match Int32.TryParse s with
| true, i -> Ok i
| false, _ -> Error "Invalid integer"
module Array =
/// Applies a function returning a Result type to every element of an array.
/// If all the applications return Result.Ok, returns an array of the results,
/// itself wrapped in Result.Ok. If any application returns Result.Error,
/// returns the first such error.
let traverseM<'T, 'R, 'E> (f : 'T -> Result<'R, 'E>) (a : 'T[]) : Result<'R[], 'E> =
let result = Array.zeroCreate a.Length
let mutable i = 0
let mutable e = ValueNone
while e.IsNone && i < a.Length do
let x = a.[i]
match f x with
| Ok r ->
result.[i] <- r
i <- i+1
| Error err ->
e <- ValueSome err
match e with
| ValueNone ->
Ok result
| ValueSome err ->
Error err
module Color =
open System.Drawing
open System.Text.RegularExpressions
let hexRe = Regex(@"[\d|A-F]{6}", RegexOptions.IgnoreCase)
/// Tries to parse a Color from a string, in the forms:
/// - Single letter (e.g. R for Red)
/// - A known .NET color (e.g. "PeachPuff")
/// - A hex value (e.g. "FF00FF").
let tryParse (s : string) : Result<Color, string> =
// TODO color modifiers L and D for Light and Dark
// TODO pick nicer colors
// TODO add all rainbow colors
if s = "R" then
Ok Color.Red
elif s = "G" then
Ok Color.Green
elif s = "B" then
Ok Color.Blue
elif s = "Y" then
Ok Color.Yellow
elif s = "K" then
Ok Color.Black
elif s = "W" then
Ok Color.White
elif s = "T" then
Ok Color.Brown
elif s = "N" then
Ok Color.Gray
else
let color = Color.FromName(s)
if color.IsKnownColor then
Ok color
elif hexRe.IsMatch(s) then
let argb = Convert.ToInt32(s, 16)
let color = Color.FromArgb(argb)
Ok color
else
Error (sprintf "Unknown colour name: %s" s)
/// Performs a naive color mix between two colors by taking weighted averages of the R G and B components.
let blend (color1Proportion : float) (color1 : Color) (color2 : Color) =
let mix (a : byte) (b : byte) =
((a |> float) * color1Proportion) + ((b |> float) * (1. - color1Proportion)) |> int
let r = mix color1.R color2.R
let g = mix color1.G color2.G
let b = mix color1.B color2.B
Color.FromArgb(r, g, b)
/// A solid band of color of a specified width.
type Band = { Color : System.Drawing.Color; Count : int }
module Band =
let private digit = [|'0'..'9'|]
/// Tries to parse the spec of one band of color, comprising a color spec and a count
/// in the forms "#ff0000#32", "Red32" or "R32".
let tryParse(s : string) =
let invalid e = Error <| sprintf "Invalid band specification: %s" e
let colorAndCount =
// "#ff0000#32"
if s.StartsWith '#' then
let parts = s.Split('#', StringSplitOptions.RemoveEmptyEntries)
match parts with
| [|colorString; countString|] ->
(colorString, countString) |> Ok
| _ ->
invalid s
// "Red32", "R32"
else
let firstDigit = s.IndexOfAny(digit)
if firstDigit > 0 then
(s.Substring(0, firstDigit), s.Substring(firstDigit)) |> Ok
else
invalid s
match colorAndCount with
| Ok(colorString, countString) ->
let color = colorString |> Color.tryParse
let count = countString |> Int.tryParse
match color, count with
| Ok col, Ok n ->
{ Color = col; Count = n } |> Ok
| Error e, _ | _, Error e ->
Error e
| Error e ->
Error e
/// Expands a color band to a sequence of repetitions of the same color.
let expand (band : Band) =
Seq.replicate band.Count band.Color
/// A tartan "Sett" - a series of color bands.
type Sett = Band[]
type RepeatStyle = Symmetrical | Asymmetrical
module Sett =
/// Tries to parse a sett from a string consisting of a series of space-separated
/// band specifications, e.g "K4 R24 K24 Y4" or "#000000#4 #ff0000#24 #000000#4 #ffff00#4"
let tryParse(s : string) : Result<Sett, _> =
s.Split(' ')
|> Array.traverseM Band.tryParse
// Returns the total number of threads in the Sett.
let width (sett : Sett) =
sett
|> Array.sumBy (fun band -> band.Count)
/// Expands a Sett into a sequence of colors. For repeatStyle = Symmetrical the Sett
/// is alternated between its expansion and its reverse. Otherwise the Sett is simply repeated.
let expand (repeatStyle : RepeatStyle) (sett : Sett) =
let repeat =
sett
|> Seq.collect Band.expand
|> Array.ofSeq
match repeatStyle with
| Symmetrical ->
let reverse = repeat |> Array.rev
Array.append repeat reverse
| Asymmetrical ->
repeat
module Weave =
open System.Drawing
type Component = Warp | Weft
/// Determines which of the Warp or the Weft is at the top
/// for a given position on the tartan.
let top (x : int) (y : int) : Component =
match ((x + y) / 2) % 2 with
| 0 -> Warp
| _ -> Weft
/// Given an array of colors, determines which color is present at
/// the specified index position. Indexes beyond the end of the
/// array are wrapped.
let colorAt i (threads : Color[]) =
threads.[i % threads.Length]
module Tartan =
open System.Drawing
/// Creates a 2D color array representing a tartan.
let create (width : int) (height : int) (topColorWeight : float) (repeatStyle : RepeatStyle) (threadCount : Sett) =
let colors = threadCount |> Sett.expand repeatStyle
Array2D.init width height (fun x y ->
let warpColor = colors |> Weave.colorAt x
let weftColor = colors |> Weave.colorAt y
match Weave.top x y with
| Weave.Component.Warp ->
if warpColor <> weftColor then
Color.blend topColorWeight warpColor weftColor
// When the two colors are the same and the Warp is on top,
// darken the results very slightly to give some texture to these
// single-coloured areas:
else
Color.blend topColorWeight warpColor weftColor
|> Color.blend 0.025 Color.Black
| _ ->
if warpColor <> weftColor then
Color.blend topColorWeight weftColor warpColor
// When the two colors are the same and the Warp is on top,
// lighten the results very slightly to give some texture to these
// single-coloured areas:
else
Color.blend topColorWeight weftColor warpColor
|> Color.blend 0.025 Color.White)
/// Converts a color array into a bitmap.
let asBitMap (threadPixels : int) (colors : Color[,]) =
let width = (colors.GetUpperBound(0)+1) * threadPixels
let height = (colors.GetUpperBound(1)+1) * threadPixels
let bitMap = new Bitmap(width, height)
colors
|> Array2D.iteri (fun x y c ->
for i in 0..threadPixels-1 do
for j in 0..threadPixels-1 do
// Could use LockBits for performance but it's much more code.
bitMap.SetPixel((x*threadPixels)+i, (y*threadPixels)+j, c))
bitMap
// Some examples. These will save to files as soon as the module is sent to FSI.
let savePath = @"c:\temp\Tartans"
// Example from https://en.wikipedia.org/wiki/Tartan
module WikipediaExample =
let threadCount = Sett.tryParse "K4 R24 K24 Y4"
let pixelsPerThread = 4
let bitMap =
threadCount
|> Result.map (fun tc ->
let size = (tc |> Sett.width) * pixelsPerThread
Tartan.create size size 0.9 Symmetrical tc)
|> Result.map (Tartan.asBitMap pixelsPerThread)
match bitMap with
| Ok b ->
b.Save(System.IO.Path.Join(savePath, "example.png"))
| Error e ->
printfn "%s" e
/// A tribute to Jackie Weaver.
module JackieWeaver =
let threadCount = Sett.tryParse "DarkSeaGreen32 DarkRed8 MistyRose32 LightGray16 CornSilk64 LightGray16 MistyRose32 DarkRed8 DarkSeaGreen32"
let pixelsPerThread = 4
let bitMap =
threadCount
|> Result.map (fun tc ->
let size = (tc |> Sett.width) * pixelsPerThread
Tartan.create size size 0.9 Symmetrical tc)
|> Result.map (Tartan.asBitMap pixelsPerThread)
match bitMap with
| Ok b ->
b.Save(System.IO.Path.Join(savePath, "JackieWeaver.png"))
| Error e ->
printfn "%s" e
/// One variation of the official Malcolm tartan - an asymmetrical tartan.
module MalcolmAncientHeavy =
let threadCount = Sett.tryParse "Black4 Gold4 Black4 AliceBlue4 Black4 MediumSeaGreen36 Black36 CornflowerBlue36 Tomato4 CornflowerBlue4 Tomato4 CornflowerBlue36 Black36 MediumSeaGreen36"
let pixelsPerThread = 4
let bitMap =
threadCount
|> Result.map (fun tc ->
let size = (tc |> Sett.width) * pixelsPerThread
Tartan.create size size 0.9 Asymmetrical tc)
|> Result.map (Tartan.asBitMap pixelsPerThread)
match bitMap with
| Ok b ->
b.Save(System.IO.Path.Join(savePath, "MalcolmAncientHeavy.png"))
| Error e ->
printfn "%s" e
/// An example showing that 'Hounds Tooth' is actually a special case of tartan.
module HoundsTooth =
let threadCount = Sett.tryParse "Moccasin4 SaddleBrown4"
let pixelsPerThread = 16
let bitMap =
threadCount
|> Result.map (fun tc ->
let size = (tc |> Sett.width) * pixelsPerThread
Tartan.create size size 0.9 Asymmetrical tc)
|> Result.map (Tartan.asBitMap pixelsPerThread)
match bitMap with
| Ok b ->
b.Save(System.IO.Path.Join(savePath, "HoundsTooth.png"))
| Error e ->
printfn "%s" e
// Call Random.generate() to generate and save a random tartan.
module Random =
/// Generate a random symmetrical tartan.
let generate() =
let r = System.Random()
let colorCount = r.Next(2, 7)
let randomColorHex() =
let rgb = r.Next(0, 256*256*256+1)
rgb.ToString("x").PadLeft(6, '0')
let randomBandWidth() = r.Next(4, 32)
let counts =
Array.init colorCount (fun _ -> sprintf "#%s#%i" (randomColorHex()) (randomBandWidth()))
let threadCountString = String.Join(" ", counts)
// TODO skip parser and allow more direct method of specifying colors.
let threadCount = threadCountString |> Sett.tryParse
let size = 512
let bitMap =
threadCount
|> Result.map (Tartan.create size size 0.9 Symmetrical)
|> Result.map (Tartan.asBitMap 4)
match bitMap with
| Ok b ->
let fileName = threadCountString.Replace(" ", "_")
b.Save(sprintf @"c:\temp\RandomTartans\%s.png" fileName)
| Error e ->
printfn "%s" e