vexyl 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1902 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Copyright 2026 Naomi Persephone Amethyst <naomi@amethyst.name>
3
+
4
+ require "digest"
5
+
6
+ module Vexyl
7
+ # Reads a document into a flag, reporting every problem it finds.
8
+ class Parser
9
+ FORMAT_VERSION = 1
10
+ # In a color list, leaves a gap, and can't be a palette name.
11
+ NO_COLOR = "none"
12
+
13
+ COLOR_VALUE = /\A#[0-9a-fA-F]{6}\z/
14
+ SERIES_VALUE = /\A[a-z0-9]+(-[a-z0-9]+)*\z/
15
+ DATE_VALUE = /\A([0-9]{4})(?:-([0-9]{2})(?:-([0-9]{2}))?)?\z/
16
+
17
+ ALONG = %w[fly hoist bend bend-sinister].freeze
18
+ FROM = %w[hoist fly top bottom].freeze
19
+ BLEND = %w[normal multiply screen overlay darken lighten].freeze
20
+ ANCHOR = %w[start center end scale].freeze
21
+ CORNER = %w[upper-hoist upper-fly lower-hoist lower-fly].freeze
22
+ RAY_FROM = %w[center hoist fly top bottom upper-hoist upper-fly lower-hoist lower-fly].freeze
23
+ SHAPE_KINDS = %w[disc ring rect plus triangle star heart cardioid polygon crescent sun lozenge ellipse
24
+ path].freeze
25
+ VIEW = %w[none rotate counter-rotate half-turn transpose anti-transpose invert mirror].freeze
26
+ MODE = %w[extend center scale hoist-extend hoist-center hoist-scale].freeze
27
+ # These put no conditions on a work, so a file adapting one can license its renders as it likes.
28
+ FREE_LICENSES = %w[CC0-1.0 LicenseRef-Public-Domain].freeze
29
+ HAS_RADIUS = %w[disc ring plus triangle star heart cardioid crescent sun].freeze
30
+ COLOR_SYSTEMS = %w[pantone ncs ral munsell dye thread].freeze
31
+ CHECKS_FLOW = %w[bend bend-sinister].freeze
32
+ MEASURE = %w[angle edge].freeze
33
+ DAYS_IN_MONTH = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31].freeze
34
+
35
+ STAGE_VERSION = 0
36
+ STAGE_META = 1
37
+ STAGE_PALETTE = 2
38
+ STAGE_PROPORTION = 3
39
+ STAGE_OUTLINE = 4
40
+ STAGE_BORDER = 5
41
+ STAGE_DEFINE = 6
42
+ STAGE_LAYERS = 7
43
+ STAGE_REVERSE = 8
44
+ STAGE_ADAPT = 9
45
+ STAGE_VARIANT = 10
46
+ STAGE_FOLD = 11
47
+ STAGES = {
48
+ "vexyl" => STAGE_VERSION, "meta" => STAGE_META, "palette" => STAGE_PALETTE,
49
+ "proportion" => STAGE_PROPORTION, "outline" => STAGE_OUTLINE, "border" => STAGE_BORDER,
50
+ "define" => STAGE_DEFINE, "reverse" => STAGE_REVERSE, "adapt" => STAGE_ADAPT,
51
+ "variant" => STAGE_VARIANT, "fold" => STAGE_FOLD
52
+ }.freeze
53
+ private_constant :STAGE_VERSION, :STAGE_META, :STAGE_PALETTE, :STAGE_PROPORTION, :STAGE_OUTLINE,
54
+ :STAGE_BORDER, :STAGE_DEFINE, :STAGE_LAYERS, :STAGE_REVERSE, :STAGE_ADAPT,
55
+ :STAGE_VARIANT, :STAGE_FOLD, :STAGES
56
+
57
+ def initialize(src)
58
+ @src = src
59
+ @problems = []
60
+ @defines = {}
61
+ @palette = {}
62
+ @gradients = {}
63
+ # Lets a gradient's colors recognize other gradients, since they're read one at a time.
64
+ @gradient_names = []
65
+ # What the flag has painted so far, as section 15 counts it.
66
+ @size = 0
67
+ # The longer side of the flag's own grid, for counting shaped edges.
68
+ @longer = 0.0
69
+ end
70
+ private_class_method :new
71
+
72
+ # Reads a document, giving its flag, or raising its problems.
73
+ def self.parse(text)
74
+ src = normalize_newlines(text)
75
+ begin
76
+ nodes = Kdl.parse(src)
77
+ rescue Kdl::SyntaxError => e
78
+ line, column = place(src, e.offset)
79
+ raise ProblemsError.new([Problem.new(line, column, nil, e.message)])
80
+ end
81
+ p = new(src)
82
+ flag = p.read(nodes)
83
+ flag.id_prefix = "vx-#{hex(Digest::SHA256.digest(src), 8)}-"
84
+ raise ProblemsError.new(p.problems) unless p.problems.empty?
85
+ flag
86
+ end
87
+
88
+ attr_reader :problems
89
+
90
+ # Reads the document's nodes, collecting its problems.
91
+ def read(nodes)
92
+ prepare(nodes)
93
+ document(nodes)
94
+ end
95
+
96
+ # Makes CRLF and a lone CR into LF, as section 4 of the format and XML both do.
97
+ def self.normalize_newlines(s)
98
+ return s unless s.include?("\r")
99
+ s.gsub("\r\n", "\n").tr("\r", "\n")
100
+ end
101
+
102
+ # The first count bytes, in lowercase hex. bytes is a binary String or an Array of Integers.
103
+ def self.hex(bytes, count)
104
+ bytes = bytes.bytes if bytes.is_a?(String)
105
+ bytes[0, count].map { |b| format("%02x", b & 0xff) }.join
106
+ end
107
+
108
+ # Finds where a character is: lines end at LF, and a column counts code points. The offset
109
+ # counts code points too. Gives [line, column].
110
+ def self.place(src, offset)
111
+ offset = [offset, src.length].min
112
+ prefix = src[0, offset]
113
+ line = 1 + prefix.count("\n")
114
+ last = prefix.rindex("\n")
115
+ [line, last ? offset - last : offset + 1]
116
+ end
117
+
118
+ def self.quote(s)
119
+ b = +"\""
120
+ s.each_char do |c|
121
+ b << "\\" if c == "\"" || c == "\\"
122
+ if c.ord < 0x20
123
+ b << format("\\x%02x", c.ord)
124
+ else
125
+ b << c
126
+ end
127
+ end
128
+ b << "\""
129
+ end
130
+
131
+ # Accepts a year, a month or a day, which is as much as many flags' origins are known to.
132
+ def self.valid_date(text)
133
+ m = DATE_VALUE.match(text)
134
+ return false unless m
135
+ year = m[1].to_i
136
+ return true if m[2].nil?
137
+ month = m[2].to_i
138
+ return false if month < 1 || month > 12
139
+ return true if m[3].nil?
140
+ day = m[3].to_i
141
+ leap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0
142
+ days = month == 2 && leap ? 29 : DAYS_IN_MONTH[month]
143
+ day >= 1 && day <= days
144
+ end
145
+
146
+ # A list as messages write it.
147
+ def self.list_text(list)
148
+ "[#{list.join(", ")}]"
149
+ end
150
+
151
+ private
152
+
153
+ def quote(s)
154
+ Parser.quote(s)
155
+ end
156
+
157
+ def list_text(list)
158
+ Parser.list_text(list)
159
+ end
160
+
161
+ def errf(n, message)
162
+ line, column = Parser.place(@src, n.start)
163
+ @problems << Problem.new(line, column, n.name, message)
164
+ end
165
+
166
+ def problem(message)
167
+ @problems << Problem.new(0, 0, nil, message)
168
+ end
169
+
170
+ # Checks what's the same wherever it is in a document.
171
+ def prepare(nodes)
172
+ nodes.each do |n|
173
+ errf(n, "type annotations aren't used by this format") if n.annotated
174
+ n.args.each { |v| errf(n, "type annotations aren't used by this format") if v.annotated }
175
+ n.props.each_value { |v| errf(n, "type annotations aren't used by this format") if v.annotated }
176
+ n.repeated_props.each { |key| errf(n, "property #{quote(key)} given more than once") }
177
+ prepare(n.children)
178
+ end
179
+ end
180
+
181
+ # Walks the top level, whose nodes have a fixed order.
182
+ def document(nodes)
183
+ flag = Model::Doc.new
184
+ @defines = flag.defines
185
+ stage = -1
186
+ seen = {}
187
+ nodes.each do |n|
188
+ s = STAGES.fetch(n.name, STAGE_LAYERS)
189
+ if s < stage || (s == stage && s != STAGE_LAYERS && s != STAGE_DEFINE && s != STAGE_VARIANT &&
190
+ s != STAGE_FOLD)
191
+ errf(n, "out of order or repeated")
192
+ next
193
+ end
194
+ if s > STAGE_VERSION && stage < STAGE_VERSION
195
+ line, column = Parser.place(@src, n.start)
196
+ @problems << Problem.new(line, column, nil, "document must start with `vexyl #{FORMAT_VERSION}`")
197
+ return flag
198
+ end
199
+ stage = s
200
+ seen[s] = true
201
+ case n.name
202
+ when "vexyl"
203
+ if number(n) != FORMAT_VERSION
204
+ errf(n, "unsupported format version; this renderer reads #{FORMAT_VERSION}")
205
+ return flag
206
+ end
207
+ flag.version = FORMAT_VERSION
208
+ when "meta"
209
+ meta(n, flag.meta)
210
+ when "palette"
211
+ palette_node(n, flag)
212
+ when "proportion"
213
+ only_args(n, 0, "hoist", "fly")
214
+ flag.hoist = positive(n, prop(n, "hoist"))
215
+ flag.fly = positive(n, prop(n, "fly"))
216
+ @longer = [flag.hoist, flag.fly].max
217
+ no_children(n)
218
+ when "outline"
219
+ flag.outline = outline(n)
220
+ when "border"
221
+ flag.border, flag.border_outside = border(n)
222
+ check_outside(n, flag.outline, flag.fly, flag.hoist, flag.border, flag.border_outside)
223
+ when "define"
224
+ define(n)
225
+ when "reverse"
226
+ reverse(n, flag)
227
+ when "adapt"
228
+ adapt(n, flag)
229
+ when "variant"
230
+ variant(n, flag)
231
+ when "fold"
232
+ fold(n, flag)
233
+ else
234
+ if flag.fly == 0 && flag.hoist == 0
235
+ errf(n, "layers must follow `proportion`")
236
+ return flag
237
+ end
238
+ l = layer(n, 1)
239
+ if l
240
+ flag.layers << l
241
+ count(n, [l])
242
+ end
243
+ end
244
+ end
245
+ problem("document must start with `vexyl #{FORMAT_VERSION}`") unless seen[STAGE_VERSION]
246
+ problem("document needs `meta`") unless seen[STAGE_META]
247
+ problem("document needs `palette`") unless seen[STAGE_PALETTE]
248
+ problem("document needs `proportion`") unless seen[STAGE_PROPORTION]
249
+ flag.variants.each do |name, v|
250
+ if v.ratio != 0 && flag.adapt.nil?
251
+ problem("variant #{quote(name)} has a `ratio`, but the flag has no `adapt` rules")
252
+ end
253
+ end
254
+ if flag.fly > 0 && flag.hoist > 0 && @problems.empty?
255
+ flag.folds.each do |name, f|
256
+ Geometry.fold_facets(Geometry.fold_shape(flag), f, 0)
257
+ rescue Vexyl::Error => e
258
+ problem("fold #{quote(name)}: #{e.message}")
259
+ end
260
+ end
261
+ flag
262
+ end
263
+
264
+ # Adds what a top-level node paints to the flag's size, refusing the node that takes it past the limit.
265
+ def count(n, layers)
266
+ was = @size
267
+ @size = Limits.add(@size, Limits.layers_size(layers, @longer))
268
+ if was <= Limits::MAX_SIZE && @size > Limits::MAX_SIZE
269
+ errf(n, "paints too much: a flag can only come to #{Limits::MAX_SIZE} parts")
270
+ end
271
+ end
272
+
273
+ # A handler that reads a child's one string and gives it to the block.
274
+ def str_h(&set)
275
+ ->(c) { set.call(str(c)) }
276
+ end
277
+
278
+ def meta(n, m)
279
+ no_values(n)
280
+ h = {
281
+ "name" => str_h { |v| m.name = v },
282
+ "description" => str_h { |v| m.description = v },
283
+ "version" => str_h { |v| m.version = v },
284
+ "date" => lambda do |c|
285
+ m.date = str(c)
286
+ if !m.date.empty? && !Parser.valid_date(m.date)
287
+ errf(c, "must be YYYY, YYYY-MM or YYYY-MM-DD, got #{quote(m.date)}")
288
+ end
289
+ end,
290
+ "until" => lambda do |c|
291
+ m.until = str(c)
292
+ if !m.until.empty? && !Parser.valid_date(m.until)
293
+ errf(c, "must be YYYY, YYYY-MM or YYYY-MM-DD, got #{quote(m.until)}")
294
+ end
295
+ end,
296
+ "series" => lambda do |c|
297
+ m.series = str(c)
298
+ if !m.series.empty? && !SERIES_VALUE.match?(m.series)
299
+ errf(c, "must be lowercase words joined by hyphens, got #{quote(m.series)}")
300
+ end
301
+ end,
302
+ "note" => str_h { |v| m.notes << v },
303
+ "law" => lambda do |c|
304
+ r = reference(c)
305
+ m.laws << r if r
306
+ end,
307
+ "restriction" => lambda do |c|
308
+ r = reference(c)
309
+ if r
310
+ errf(c, "needs a `source`, since an unsourced legal claim can mislead") if r.sources.empty?
311
+ m.restrictions << r
312
+ end
313
+ end,
314
+ "designer" => str_h { |v| m.designers << v },
315
+ "design-rights" => str_h { |v| m.design_rights = v },
316
+ "encoder" => str_h { |v| m.encoders << v },
317
+ "license" => str_h { |v| m.license = v },
318
+ "render-license" => str_h { |v| m.render_license = v },
319
+ "adapted-from" => lambda do |c|
320
+ a = adaptation(c)
321
+ m.adapted_from << a if a
322
+ end,
323
+ "source" => str_h { |v| m.sources << v }
324
+ }
325
+ children(n, %w[designer encoder source note law restriction adapted-from], h)
326
+ unless m.render_license.empty?
327
+ m.adapted_from.each do |a|
328
+ if a.license != m.render_license && !FREE_LICENSES.include?(a.license)
329
+ errf(n, "`render-license` #{quote(m.render_license)} can't cover work adapted from #{a.url} " \
330
+ "under #{quote(a.license)}")
331
+ end
332
+ end
333
+ end
334
+ errf(n, "needs a `name`") if m.name.empty?
335
+ if !m.date.empty? && !m.until.empty?
336
+ # Each is only known to its own precision, so they compare only as far as both go.
337
+ shared = [m.date.length, m.until.length].min
338
+ errf(n, "`until` comes before `date`") if m.until[0, shared] < m.date[0, shared]
339
+ end
340
+ end
341
+
342
+ def adaptation(n)
343
+ no_props(n)
344
+ if n.args.size != 1 || !n.args[0].string?
345
+ errf(n, "needs the URL of the original work")
346
+ return nil
347
+ end
348
+ a = Model::Adaptation.new
349
+ a.url = n.args[0].string
350
+ h = {
351
+ "author" => str_h { |v| a.authors << v },
352
+ "license" => str_h { |v| a.license = v },
353
+ "part" => str_h { |v| a.part = v }
354
+ }
355
+ children(n, ["author"], h)
356
+ a
357
+ end
358
+
359
+ def palette_node(n, flag)
360
+ no_values(n)
361
+ @palette = flag.palette
362
+ @gradients = flag.gradients
363
+ # Gradients can name colors defined after them, so they're read second.
364
+ later = []
365
+ seen = {}
366
+ n.children.each do |c|
367
+ if seen[c.name]
368
+ errf(c, "color defined twice")
369
+ next
370
+ end
371
+ if c.name == NO_COLOR
372
+ errf(c, "#{quote(NO_COLOR)} is reserved for leaving a gap")
373
+ next
374
+ end
375
+ if c.name.empty?
376
+ errf(c, "a color's name can't be empty")
377
+ next
378
+ end
379
+ seen[c.name] = true
380
+ if !c.args.empty? && c.args[0].string? && c.args[0].string == "gradient"
381
+ later << c
382
+ next
383
+ end
384
+ value = color(c, flag)
385
+ errf(c, "color must be #rrggbb, got #{quote(value)}") unless COLOR_VALUE.match?(value)
386
+ # Either case means the same, so the model has only one.
387
+ flag.palette[c.name] = value.downcase
388
+ end
389
+ later.each { |c| @gradient_names << c.name }
390
+ later.each { |c| flag.gradients[c.name] = gradient(c) }
391
+ end
392
+
393
+ # Reads `name gradient COLOR... along=AXIS { stops N... }`.
394
+ def gradient(n)
395
+ g = Model::Gradient.new
396
+ n.args[1..].each do |a|
397
+ unless a.string?
398
+ errf(n, "a gradient's colors must be palette names")
399
+ next
400
+ end
401
+ g.colors << solid_color(n, a.string)
402
+ end
403
+ errf(n, "a gradient needs at least 2 colors") if g.colors.size < 2
404
+ n.props.each_key { |key| errf(n, "unknown property #{quote(key)}") if key != "along" }
405
+ v = n.prop("along")
406
+ if v
407
+ if !v.string? || !ALONG.include?(v.string)
408
+ errf(n, "along must be one of #{list_text(ALONG)}")
409
+ else
410
+ g.along = v.string
411
+ end
412
+ end
413
+ children(n, [], { "stops" => ->(c) { g.stops = stops(c, g.colors.size) } })
414
+ if g.stops.nil?
415
+ d = [g.colors.size - 1, 1].max
416
+ g.stops = Array.new(g.colors.size) { |i| i.to_f / d }
417
+ end
418
+ g
419
+ end
420
+
421
+ def stops(n, count)
422
+ stops = numbers(n)
423
+ errf(n, "has #{count} colors but #{stops.size} stops") if stops.size != count
424
+ stops.each_with_index do |s, i|
425
+ errf(n, "stops must be between 0 and 1") if s < 0 || s > 1
426
+ errf(n, "stops can't run backward") if i > 0 && s < stops[i - 1]
427
+ end
428
+ stops
429
+ end
430
+
431
+ # Reads a palette color, with its values in any other color systems.
432
+ def color(n, flag)
433
+ no_props(n)
434
+ if n.args.size != 1 || !n.args[0].string?
435
+ errf(n, "needs one string")
436
+ return ""
437
+ end
438
+ refs = []
439
+ named = lambda do |c|
440
+ r = Model::ColorRef.new
441
+ r.system = c.name
442
+ r.value = str(c)
443
+ refs << r
444
+ end
445
+ h = {}
446
+ COLOR_SYSTEMS.each { |system| h[system] = named }
447
+ h["cmyk"] = lambda do |c|
448
+ v = numbers(c)
449
+ if v.size != 4
450
+ errf(c, "needs 4 values from 0 to 100")
451
+ return
452
+ end
453
+ parts = v.map do |x|
454
+ errf(c, "needs 4 values from 0 to 100") if x < 0 || x > 100
455
+ Json.number(x)
456
+ end
457
+ r = Model::ColorRef.new
458
+ r.system = "cmyk"
459
+ r.value = parts.join(" ")
460
+ r.numbers = v
461
+ refs << r
462
+ end
463
+ h["reference"] = lambda do |c|
464
+ no_props(c)
465
+ no_children(c)
466
+ if c.args.size != 2 || !c.args[0].string? || !c.args[1].string?
467
+ errf(c, "needs a system's name and a value")
468
+ return
469
+ end
470
+ r = Model::ColorRef.new
471
+ r.system = c.args[0].string
472
+ r.value = c.args[1].string
473
+ r.other = true
474
+ refs << r
475
+ end
476
+ children(n, %w[dye reference], h)
477
+ flag.color_refs[n.name] = refs unless refs.empty?
478
+ n.args[0].string
479
+ end
480
+
481
+ def layer(n, depth)
482
+ if depth > Limits::MAX_DEPTH
483
+ errf(n, "nested more than #{Limits::MAX_DEPTH} levels deep")
484
+ return nil
485
+ end
486
+ case n.name
487
+ when "field"
488
+ l = Model::Field.new
489
+ l.color = color_arg(n)
490
+ no_props(n)
491
+ children(n, ["cut"], with_effects(l, nil))
492
+ l
493
+ when "bars" then bars(n)
494
+ when "chevrons" then chevrons(n)
495
+ when "band" then band(n)
496
+ when "cross" then cross(n)
497
+ when "saltire" then saltire(n)
498
+ when "charge" then charge(n)
499
+ when "quarters" then quarters(n)
500
+ when "checks" then checks(n)
501
+ when "rays" then rays(n)
502
+ when "pile", "pall" then ordinary_shape(n)
503
+ when "panel" then panel(n, depth)
504
+ when "use" then use(n, depth)
505
+ when "emblem" then emblem(n)
506
+ when "group"
507
+ l = Model::Group.new
508
+ no_values(n)
509
+ container(n, depth, l, l.layers, nil)
510
+ errf(n, "needs at least one layer") if l.layers.empty?
511
+ l
512
+ when "canton"
513
+ l = Model::Panel.new
514
+ l.corner = "upper-hoist"
515
+ l.canton = true
516
+ no_values(n)
517
+ h = {
518
+ "fly" => ->(c) { l.fly = positive(c, number(c)) },
519
+ "hoist" => ->(c) { l.hoist = positive(c, number(c)) }
520
+ }
521
+ container(n, depth, l, l.layers, h)
522
+ errf(n, "needs `fly` and `hoist`") if l.fly == 0 || l.hoist == 0
523
+ errf(n, "needs at least one layer") if l.layers.empty?
524
+ l
525
+ else
526
+ errf(n, "unknown layer")
527
+ nil
528
+ end
529
+ end
530
+
531
+ # Reads a group, panel or canton, whose children mix settings and layers.
532
+ def container(n, depth, e, layers, settings)
533
+ handlers = with_effects(e, settings)
534
+ seen = {}
535
+ n.children.each do |c|
536
+ handler = handlers[c.name]
537
+ if handler.nil?
538
+ l = layer(c, depth + 1)
539
+ layers << l if l
540
+ next
541
+ end
542
+ errf(c, "given more than once") if seen[c.name] && c.name != "cut"
543
+ seen[c.name] = true
544
+ handler.call(c)
545
+ end
546
+ end
547
+
548
+ def with_effects(e, handlers)
549
+ merged = {
550
+ "opacity" => lambda do |c|
551
+ e.opacity = number(c)
552
+ errf(c, "must be between 0 and 1") if e.opacity < 0 || e.opacity > 1
553
+ end,
554
+ "blend" => ->(c) { e.blend = one_of(c, BLEND) },
555
+ "anchor" => ->(c) { e.anchor = one_of(c, ANCHOR) },
556
+ "clip" => lambda do |c|
557
+ s = mask_shape(c)
558
+ e.clip = s if s
559
+ end,
560
+ "cut" => lambda do |c|
561
+ s = mask_shape(c)
562
+ e.cuts << s if s
563
+ end
564
+ }
565
+ merged.merge!(handlers) if handlers
566
+ merged
567
+ end
568
+
569
+ # Reads the single shape inside a clip or cut.
570
+ def mask_shape(n)
571
+ no_values(n)
572
+ if n.children.size != 1
573
+ errf(n, "needs exactly one shape")
574
+ return nil
575
+ end
576
+ c = n.children[0]
577
+ no_values(c)
578
+ if c.name == "svg"
579
+ errf(c, "inline SVG can't be used as a clip or cut")
580
+ return nil
581
+ end
582
+ s = named_shape(c.name)
583
+ shape_body(c, s, nil)
584
+ if s.hollow > 0 || s.lines > 0
585
+ errf(c, "a clip or cut uses a shape's whole area, so it can't be `hollow` or `lines`")
586
+ end
587
+ s
588
+ end
589
+
590
+ # Starts a shape of a kind, or from a definition of that name.
591
+ def named_shape(name)
592
+ d = @defines[name]
593
+ if d && d.shape
594
+ s = d.shape.copy
595
+ s.vertices = s.vertices.dup
596
+ return s
597
+ end
598
+ s = Model::Shape.new
599
+ s.kind = name
600
+ s
601
+ end
602
+
603
+ def bars(n)
604
+ l = Model::Bars.new
605
+ l.colors = gap_color_args(n)
606
+ no_props(n)
607
+ count = 0
608
+ h = {
609
+ "along" => ->(c) { l.along = one_of(c, ALONG) },
610
+ "ratio" => ->(c) { l.ratio = positives(c) },
611
+ "rotate" => ->(c) { l.rotate = number(c) },
612
+ "count" => ->(c) { count = integer(c, number(c), Limits::MAX_COPIES) },
613
+ "grow" => ->(c) { l.grow = numbers(c) },
614
+ "edge" => ->(c) { l.line = line(c) }
615
+ }
616
+ children(n, ["cut"], with_effects(l, h))
617
+ return l if l.colors.empty?
618
+ l.colors = cycle(n, l.colors, count)
619
+ check_waves(n, l.line)
620
+ l.ratio = ratio(n, l.ratio, l.colors.size)
621
+ if l.grow && l.grow.size != l.colors.size
622
+ errf(n, "has #{l.colors.size} colors but #{l.grow.size} `grow` values")
623
+ end
624
+ l.grow&.each { |g| errf(n, "`grow` can't be negative") if g < 0 }
625
+ if l.grow && l.rotate != 0
626
+ errf(n, "a rotated bars keeps its widths at other proportions, so it takes no `grow`")
627
+ end
628
+ l
629
+ end
630
+
631
+ def chevrons(n)
632
+ l = Model::Chevrons.new
633
+ l.colors = gap_color_args(n)
634
+ no_props(n)
635
+ h = {
636
+ "from" => ->(c) { l.from = one_of(c, FROM) },
637
+ "depth" => ->(c) { l.depth = positive(c, number(c)) },
638
+ "angle" => lambda do |c|
639
+ l.angle = number(c)
640
+ errf(c, "must be between 0 and 90 degrees, exclusive") if l.angle <= 0 || l.angle >= 90
641
+ end,
642
+ "apex" => lambda do |c|
643
+ apex = number(c)
644
+ errf(c, "can't be negative") if apex < 0
645
+ l.apex = apex
646
+ end,
647
+ "ratio" => ->(c) { l.ratio = positives(c) },
648
+ "rotate" => ->(c) { l.rotate = number(c) },
649
+ "fimbriate" => ->(c) { l.fimbriate = edge(c) }
650
+ }
651
+ children(n, ["cut"], with_effects(l, h))
652
+ errf(n, "needs a `depth`") if l.depth == 0
653
+ if !l.apex.nil? && l.angle == 0
654
+ errf(n, "an off-center `apex` needs an `angle`, since its arms can't meet both corners at one slope")
655
+ end
656
+ l.ratio = ratio(n, l.ratio, l.colors.size)
657
+ l
658
+ end
659
+
660
+ # Repeats colors until there are count of them, if count is given. Fewer would drop some silently.
661
+ def cycle(n, colors, count)
662
+ return colors if count == 0
663
+ if count < colors.size
664
+ errf(n, "has #{colors.size} colors but a `count` of #{count}, which would leave some out")
665
+ return colors
666
+ end
667
+ Array.new(count) { |i| colors[i % colors.size] }
668
+ end
669
+
670
+ def check_waves(n, l)
671
+ if l && l.waves(@longer) > Limits::MAX_COPIES
672
+ errf(n, "a shaped edge can't have more than #{Limits::MAX_COPIES} waves")
673
+ end
674
+ end
675
+
676
+ def ratio(n, ratio, count)
677
+ ratio = Array.new(count, 1.0) if ratio.nil?
678
+ errf(n, "has #{count} colors but a ratio of #{ratio.size} values") if ratio.size != count
679
+ ratio
680
+ end
681
+
682
+ def band(n)
683
+ l = Model::Band.new
684
+ l.color = color_arg(n)
685
+ no_props(n)
686
+ h = {
687
+ "along" => ->(c) { l.along = one_of(c, ALONG) },
688
+ "width" => ->(c) { l.width = positive(c, number(c)) },
689
+ "offset" => ->(c) { l.offset = number(c) },
690
+ "rotate" => ->(c) { l.rotate = number(c) },
691
+ "fimbriate" => ->(c) { l.fimbriate = edge(c) }
692
+ }
693
+ children(n, ["cut"], with_effects(l, h))
694
+ errf(n, "needs a `width`") if l.width == 0
695
+ l
696
+ end
697
+
698
+ def cross(n)
699
+ l = Model::Cross.new
700
+ l.color = color_arg(n)
701
+ no_props(n)
702
+ seen_fly = false
703
+ seen_hoist = false
704
+ h = {
705
+ "fly" => lambda do |c|
706
+ l.fly_parts = triple(c)
707
+ seen_fly = true
708
+ end,
709
+ "hoist" => lambda do |c|
710
+ l.hoist_parts = triple(c)
711
+ seen_hoist = true
712
+ end,
713
+ "fimbriate" => ->(c) { l.fimbriate = edge(c) }
714
+ }
715
+ children(n, ["cut"], with_effects(l, h))
716
+ errf(n, "needs `fly` and `hoist`") if !seen_fly || !seen_hoist
717
+ l
718
+ end
719
+
720
+ # Reads the distance before an arm, its width and the distance after.
721
+ def triple(n)
722
+ v = numbers(n)
723
+ if v.size != 3
724
+ errf(n, "needs 3 values: before the arm, its width, and after it")
725
+ return [0.0, 1.0, 0.0]
726
+ end
727
+ if v[0] < 0 || v[1] <= 0 || v[2] < 0
728
+ errf(n, "the arm's width must be positive and its distances not negative")
729
+ return [0.0, 1.0, 0.0]
730
+ end
731
+ v
732
+ end
733
+
734
+ def saltire(n)
735
+ l = Model::Saltire.new
736
+ l.color = color_arg(n)
737
+ no_props(n)
738
+ h = {
739
+ "width" => ->(c) { l.width = positive(c, number(c)) },
740
+ "fimbriate" => ->(c) { l.fimbriate = edge(c) },
741
+ "counterchange" => ->(c) { l.counterchange = flag_value(c) }
742
+ }
743
+ children(n, ["cut"], with_effects(l, h))
744
+ errf(n, "needs a `width`") if l.width == 0
745
+ errf(n, "a counterchanged saltire can't be fimbriated") if l.counterchange && l.fimbriate
746
+ l
747
+ end
748
+
749
+ def charge(n)
750
+ args = n.args
751
+ no_props(n)
752
+ if args.empty? || !args[0].string?
753
+ errf(n, "needs a shape")
754
+ return nil
755
+ end
756
+ name = args[0].string
757
+ if name == "pile" || name == "pall"
758
+ errf(n, "a #{name} is a layer of its own, not a charge's shape")
759
+ return nil
760
+ end
761
+ l = Model::Charge.new
762
+ l.shape = named_shape(name)
763
+ if l.shape.kind == "svg" && args.size == 1
764
+ # Inline SVG can bring its own colors.
765
+ elsif args.size != 2
766
+ errf(n, "needs a shape and a color")
767
+ return nil
768
+ elsif !args[1].string?
769
+ errf(n, "color must be a palette name")
770
+ return nil
771
+ elsif l.shape.kind == "svg"
772
+ l.color = solid_color(n, args[1].string)
773
+ else
774
+ l.color = palette_color(n, args[1].string)
775
+ end
776
+ h = {
777
+ "fimbriate" => ->(c) { l.fimbriate = edge(c) },
778
+ "repeat" => ->(c) { l.repeat = repeat(c) }
779
+ }
780
+ shape_body(n, l.shape, with_effects(l, h))
781
+ s = l.shape
782
+ if s.embedded && l.color.empty? && s.embedded.uses_current_color?
783
+ errf(n, "inline SVG uses currentColor, so it needs a palette color")
784
+ elsif s.kind == "svg" && l.fimbriate
785
+ errf(n, "inline SVG can't be fimbriated")
786
+ elsif l.fimbriate && (s.hollow > 0 || s.lines > 0)
787
+ errf(n, "fimbriation edges a filled shape, so it can't go with `hollow` or `lines`")
788
+ elsif s.kind == "svg" && l.repeat
789
+ errf(n, "inline SVG can't be repeated")
790
+ elsif s.kind == "polygon" && l.repeat
791
+ errf(n, "a polygon can't be repeated")
792
+ elsif l.repeat && s.ats.size > 1
793
+ errf(n, "several positions and a repeat can't be combined")
794
+ elsif s.kind == "svg" && s.ats.size > 1
795
+ errf(n, "inline SVG can't be repeated")
796
+ elsif l.repeat && l.repeat.kind == "grid" && s.placed
797
+ errf(n, "a grid repeat spreads across the region, so it can't have `at`")
798
+ end
799
+ l
800
+ end
801
+
802
+ def emblem(n)
803
+ l = Model::Emblem.new
804
+ no_values(n)
805
+ h = {
806
+ "at" => ->(c) { l.at = at(c) },
807
+ "along" => ->(c) { l.along = one_of(c, ALONG) },
808
+ "rotate" => ->(c) { l.rotate = number(c) }
809
+ }
810
+ placed = with_effects(l, h)
811
+ seen = {}
812
+ n.children.each do |c|
813
+ if c.name == "charge"
814
+ got = layer(c, 1)
815
+ if got.is_a?(Model::Charge)
816
+ if got.repeat && got.repeat.kind == "grid"
817
+ errf(c, "a grid repeat needs a region, which an emblem doesn't have")
818
+ end
819
+ frame_shape(c, got.shape)
820
+ frame_shape(c, got.clip) if got.clip
821
+ got.cuts.each { |cut| frame_shape(c, cut) }
822
+ l.charges << got
823
+ end
824
+ next
825
+ end
826
+ handler = placed[c.name]
827
+ if handler.nil?
828
+ errf(c, "an emblem can only hold charges")
829
+ next
830
+ end
831
+ errf(c, "given more than once") if seen[c.name] && c.name != "cut"
832
+ seen[c.name] = true
833
+ handler.call(c)
834
+ end
835
+ errf(n, "needs at least one charge") if l.charges.empty?
836
+ l
837
+ end
838
+
839
+ # Refuses what needs a region's size, which an emblem's frame doesn't have.
840
+ def frame_shape(n, s)
841
+ if s.kind == "lozenge" && (s.fly == 0 || s.hoist == 0)
842
+ errf(n, "a lozenge in an emblem needs `fly` and `hoist`, since a frame has no size to take")
843
+ elsif s.kind == "pile" || s.kind == "pall"
844
+ errf(n, "a #{s.kind} needs a region's edges, which an emblem doesn't have")
845
+ end
846
+ end
847
+
848
+ def repeat(n)
849
+ no_children(n)
850
+ if n.args.size != 1 || !n.args[0].string?
851
+ errf(n, "needs a kind: ring or grid")
852
+ return nil
853
+ end
854
+ r = Model::Repeat.new
855
+ r.kind = n.args[0].string
856
+ case r.kind
857
+ when "ring"
858
+ only_args(n, 1, "count", "radius", "turn")
859
+ r.count = integer(n, prop(n, "count"), Limits::MAX_COPIES)
860
+ r.radius = positive(n, prop(n, "radius"))
861
+ r.turn = bool_prop(n, "turn")
862
+ when "grid"
863
+ only_args(n, 1, "rows", "columns", "stagger")
864
+ r.rows = integer(n, prop(n, "rows"), Limits::MAX_COPIES)
865
+ r.columns = integer(n, prop(n, "columns"), Limits::MAX_COPIES)
866
+ r.stagger = bool_prop(n, "stagger")
867
+ errf(n, "makes more than #{Limits::MAX_COPIES} copies") if r.rows * r.columns > Limits::MAX_COPIES
868
+ when "line"
869
+ only_args(n, 1, "count", "fly", "hoist")
870
+ r.count = integer(n, prop(n, "count"), Limits::MAX_COPIES)
871
+ v = n.prop("fly")
872
+ r.fly = number_value(n, v) if v
873
+ v = n.prop("hoist")
874
+ r.hoist = number_value(n, v) if v
875
+ errf(n, "needs a step: fly= or hoist=") if r.fly == 0 && r.hoist == 0
876
+ when "arc"
877
+ only_args(n, 1, "count", "radius", "turn", "from", "to")
878
+ r.count = integer(n, prop(n, "count"), Limits::MAX_COPIES)
879
+ r.radius = positive(n, prop(n, "radius"))
880
+ r.turn = bool_prop(n, "turn")
881
+ r.from = prop(n, "from")
882
+ r.to = prop(n, "to")
883
+ errf(n, "an arc needs at least 2 copies") if r.count < 2 && r.count != 0
884
+ if n.prop("from") && n.prop("to") && (r.to - r.from) % 360 == 0
885
+ errf(n, "`from` and `to` are the same place, so there's no arc to repeat along")
886
+ end
887
+ else
888
+ errf(n, "unknown repeat #{quote(r.kind)}")
889
+ end
890
+ r
891
+ end
892
+
893
+ # Reads a shape's children, along with any extra handlers.
894
+ def shape_body(n, s, extra)
895
+ h = {
896
+ "at" => lambda do |c|
897
+ at = at(c)
898
+ s.at = at unless s.placed
899
+ s.placed = true
900
+ s.ats << at
901
+ end,
902
+ "rotate" => ->(c) { s.rotate = number(c) },
903
+ "hollow" => ->(c) { s.hollow = positive(c, number(c)) }
904
+ }
905
+ s.placed = false
906
+ s.ats = []
907
+ # What was only worked out from a definition's other values is worked out again.
908
+ if s.auto_inner
909
+ s.inner = 0.0
910
+ s.auto_inner = false
911
+ end
912
+ if s.auto_spread
913
+ s.spread = 0.0
914
+ s.auto_spread = false
915
+ end
916
+ radius = ->(c) { s.radius = positive(c, number(c)) }
917
+ inner = ->(c) { s.inner = positive(c, number(c)) }
918
+ size_fly = ->(c) { s.fly = positive(c, number(c)) }
919
+ size_hoist = ->(c) { s.hoist = positive(c, number(c)) }
920
+ case s.kind
921
+ when "disc", "triangle", "cardioid"
922
+ h["radius"] = radius
923
+ when "crescent"
924
+ h["radius"] = radius
925
+ h["inner"] = inner
926
+ h["offset"] = ->(c) { s.offset = positive(c, number(c)) }
927
+ when "sun"
928
+ s.points = 12 if s.points == 0
929
+ s.spread = 1.0 if s.spread == 0
930
+ h["radius"] = radius
931
+ h["disc"] = ->(c) { s.disc = positive(c, number(c)) }
932
+ h["gap"] = ->(c) { s.gap = not_negative(c, number(c)) }
933
+ h["points"] = ->(c) { s.points = integer(c, number(c), Limits::MAX_COPIES) }
934
+ h["spread"] = ->(c) { s.spread = positive(c, number(c)) }
935
+ when "lozenge", "ellipse", "rect"
936
+ h["fly"] = size_fly
937
+ h["hoist"] = size_hoist
938
+ when "path"
939
+ h["fly"] = size_fly
940
+ h["hoist"] = size_hoist
941
+ h["d"] = ->(c) { s.d = path_data(c) }
942
+ h["box"] = ->(c) { s.box = box_value(c, str(c)) }
943
+ h["evenodd"] = ->(c) { s.even_odd = flag_value(c) }
944
+ when "pile"
945
+ h.delete("at")
946
+ h.delete("rotate")
947
+ s.edge = "hoist" if s.edge.empty?
948
+ h["from"] = ->(c) { s.edge = one_of(c, FROM) }
949
+ h["base"] = lambda do |c|
950
+ v = numbers(c)
951
+ if v.size == 2
952
+ s.base = v
953
+ else
954
+ errf(c, "needs 2 values: where it starts and ends along the edge")
955
+ end
956
+ end
957
+ h["tip"] = lambda do |c|
958
+ v = numbers(c)
959
+ if v.size == 2
960
+ s.tip = v
961
+ else
962
+ errf(c, "needs 2 values: along the edge, then in from it")
963
+ end
964
+ end
965
+ h["depth"] = ->(c) { s.depth = positive(c, number(c)) }
966
+ h["flat"] = lambda do |c|
967
+ s.flat = not_negative(c, number(c))
968
+ s.has_flat = true
969
+ end
970
+ when "pall"
971
+ h.delete("at")
972
+ h.delete("rotate")
973
+ s.edge = "hoist" if s.edge.empty?
974
+ h["from"] = ->(c) { s.edge = one_of(c, FROM) }
975
+ h["width"] = ->(c) { s.width = positive(c, number(c)) }
976
+ h["junction"] = ->(c) { s.junction = positive(c, number(c)) }
977
+ when "heart"
978
+ h["radius"] = radius
979
+ h["spread"] = ->(c) { s.spread = positive(c, number(c)) }
980
+ when "ring"
981
+ h["radius"] = radius
982
+ h["inner"] = inner
983
+ h["from"] = lambda do |c|
984
+ s.from = number(c)
985
+ s.has_arc = true
986
+ end
987
+ h["to"] = lambda do |c|
988
+ s.to = number(c)
989
+ s.has_arc = true
990
+ end
991
+ when "plus"
992
+ h["radius"] = radius
993
+ h["width"] = ->(c) { s.width = positive(c, number(c)) }
994
+ when "star"
995
+ s.points = 5 if s.points == 0
996
+ h["radius"] = radius
997
+ h["inner"] = inner
998
+ h["lines"] = ->(c) { s.lines = positive(c, number(c)) }
999
+ h["points"] = lambda do |c|
1000
+ s.points = integer(c, number(c), Limits::MAX_COPIES)
1001
+ errf(c, "needs at least 3 points") if s.points > 0 && s.points < 3
1002
+ end
1003
+ when "polygon"
1004
+ h.delete("at")
1005
+ h.delete("rotate")
1006
+ h["point"] = lambda do |c|
1007
+ only_args(c, 0, "fly", "hoist")
1008
+ no_children(c)
1009
+ s.vertices << Model::Point.new(prop(c, "fly"), prop(c, "hoist"))
1010
+ end
1011
+ when "svg"
1012
+ h["fly"] = size_fly
1013
+ h["hoist"] = size_hoist
1014
+ h["markup"] = ->(c) { s.markup = str(c) }
1015
+ else
1016
+ errf(n, "unknown shape #{quote(s.kind)}")
1017
+ return
1018
+ end
1019
+ h.merge!(extra) if extra
1020
+ repeatable = %w[cut point]
1021
+ repeatable << "at" if extra
1022
+ h.delete("hollow") if s.kind == "svg"
1023
+ children(n, repeatable, h)
1024
+ check_shape(n, s)
1025
+ end
1026
+
1027
+ def check_shape(n, s)
1028
+ errf(n, "needs a `radius`") if HAS_RADIUS.include?(s.kind) && s.radius == 0
1029
+ case s.kind
1030
+ when "ring"
1031
+ errf(n, "needs an `inner` smaller than its `radius`") if s.inner == 0 || s.inner >= s.radius
1032
+ if s.has_arc && (s.to - s.from) % 360 == 0
1033
+ errf(n, "`from` and `to` are the same place, so there's no arc to draw")
1034
+ end
1035
+ when "star"
1036
+ errf(n, "`lines` and `hollow` can't be combined") if s.lines > 0 && s.hollow > 0
1037
+ errf(n, "`lines` needs at least 5 points") if s.lines > 0 && s.points < 5
1038
+ errf(n, "`inner` must be smaller than `radius`") if s.inner >= s.radius && s.radius > 0
1039
+ errf(n, "needs an `inner` with fewer than 5 points") if s.inner == 0 && s.points < 5
1040
+ if s.inner == 0
1041
+ k = s.points.to_f
1042
+ s.inner = s.radius * Math.cos(2 * Math::PI / k) / Math.cos(Math::PI / k)
1043
+ s.auto_inner = true
1044
+ end
1045
+ when "rect", "ellipse"
1046
+ errf(n, "needs `fly` and `hoist`") if s.fly == 0 || s.hoist == 0
1047
+ when "crescent"
1048
+ if s.inner == 0 || s.offset == 0
1049
+ errf(n, "needs `inner` and `offset`")
1050
+ elsif s.radius > 0 && (s.offset >= s.radius + s.inner || s.offset <= (s.radius - s.inner).abs)
1051
+ errf(n, "`offset` has to make its two circles cross")
1052
+ end
1053
+ when "sun"
1054
+ errf(n, "needs a `disc`") if s.disc == 0
1055
+ errf(n, "`disc` and `gap` must be smaller than `radius`") if s.radius > 0 && s.disc + s.gap >= s.radius
1056
+ errf(n, "needs at least 3 points") if s.points < 3 && s.points != 0
1057
+ errf(n, "`spread` can't be more than 1") if s.spread > 1
1058
+ when "path"
1059
+ errf(n, "needs `d`") if s.d.empty?
1060
+ errf(n, "needs a `box` with an area") if s.box[2] <= 0 || s.box[3] <= 0
1061
+ errf(n, "needs `fly` or `hoist`") if s.fly == 0 && s.hoist == 0
1062
+ when "pile"
1063
+ if s.tip.nil? && s.depth == 0
1064
+ errf(n, "needs a `depth` or a `tip`")
1065
+ elsif s.tip && s.depth != 0
1066
+ errf(n, "takes a `depth` or a `tip`, not both")
1067
+ elsif s.tip && s.has_flat
1068
+ errf(n, "a `flat` goes with a `depth`, not a `tip`")
1069
+ end
1070
+ when "pall"
1071
+ errf(n, "needs a `width`") if s.width == 0
1072
+ when "heart"
1073
+ if s.spread == 0
1074
+ s.spread = s.radius * Math.sqrt(2)
1075
+ s.auto_spread = true
1076
+ end
1077
+ if s.spread >= 2 * s.radius && s.radius > 0
1078
+ errf(n, "`spread` must be less than twice `radius`, so that the lobes meet")
1079
+ end
1080
+ when "plus"
1081
+ errf(n, "needs a `width` less than twice its `radius`") if s.width == 0 || s.width >= 2 * s.radius
1082
+ when "polygon"
1083
+ errf(n, "needs at least 3 `point`s") if s.vertices.size < 3
1084
+ when "svg"
1085
+ errf(n, "needs `fly` and `hoist`") if s.fly == 0 || s.hoist == 0
1086
+ if s.markup.empty?
1087
+ errf(n, "needs `markup`")
1088
+ return
1089
+ end
1090
+ begin
1091
+ s.embedded = Sanitizer.sanitize(s.markup)
1092
+ rescue Vexyl::Error => e
1093
+ errf(n, e.message)
1094
+ return
1095
+ end
1096
+ # Only what passed is kept, so that nothing can read what the sanitizer removed.
1097
+ s.markup = s.embedded.canonical
1098
+ end
1099
+ end
1100
+
1101
+ def at(n)
1102
+ no_children(n)
1103
+ unless n.args.empty?
1104
+ if n.args.size != 1 || !n.args[0].string? || n.args[0].string != "center" || !n.props.empty?
1105
+ errf(n, "must be `center` or `fly=A hoist=B`")
1106
+ end
1107
+ return nil
1108
+ end
1109
+ only_args(n, 0, "fly", "hoist")
1110
+ Model::Point.new(prop(n, "fly"), prop(n, "hoist"))
1111
+ end
1112
+
1113
+ # Reads `border COLOR W`, with an optional side of inside or outside. Gives [edge, outside].
1114
+ def border(n)
1115
+ args = n.args
1116
+ outside = false
1117
+ if args.size == 3
1118
+ side = args[2]
1119
+ if !side.string? || (side.string != "inside" && side.string != "outside")
1120
+ errf(n, "side must be inside or outside")
1121
+ return [nil, false]
1122
+ end
1123
+ outside = side.string == "outside"
1124
+ args = args[0, 2]
1125
+ end
1126
+ [edge_args(n, args), outside]
1127
+ end
1128
+
1129
+ # Refuses an outside border that can't go around the shape it's given.
1130
+ def check_outside(n, o, fly, hoist, border, outside)
1131
+ return if border.nil? || !outside || border.width <= 0 || fly <= 0 || hoist <= 0
1132
+ shape = o.nil? ? Geometry.rect_poly(0.0, 0.0, fly, hoist) : Geometry.outline_points(o, fly, hoist)
1133
+ if shape.nil?
1134
+ errf(n, "an outside border can't go around a `path` outline")
1135
+ return
1136
+ end
1137
+ begin
1138
+ Geometry.offset_polygon(shape, border.width)
1139
+ rescue Vexyl::Error => e
1140
+ errf(n, e.message)
1141
+ end
1142
+ end
1143
+
1144
+ def edge(n)
1145
+ edge_args(n, n.args)
1146
+ end
1147
+
1148
+ def edge_args(n, args)
1149
+ no_props(n)
1150
+ no_children(n)
1151
+ if args.size != 2 || !args[0].string?
1152
+ errf(n, "needs a color and a width")
1153
+ return nil
1154
+ end
1155
+ color = palette_color(n, args[0].string)
1156
+ Model::Edge.new(color, positive(n, number_value(n, args[1])))
1157
+ end
1158
+
1159
+ # Dispatches n's children to handlers, refusing unknown nodes and repeats of anything not repeatable.
1160
+ def children(n, repeatable, handlers)
1161
+ seen = {}
1162
+ n.children.each do |c|
1163
+ handler = handlers[c.name]
1164
+ if handler.nil?
1165
+ errf(c, "unknown here")
1166
+ next
1167
+ end
1168
+ errf(c, "given more than once") if seen[c.name] && !repeatable.include?(c.name)
1169
+ seen[c.name] = true
1170
+ handler.call(c)
1171
+ end
1172
+ end
1173
+
1174
+ def no_values(n)
1175
+ errf(n, "takes no arguments") unless n.args.empty?
1176
+ no_props(n)
1177
+ end
1178
+
1179
+ def no_props(n)
1180
+ errf(n, "takes no properties") unless n.props.empty?
1181
+ end
1182
+
1183
+ def no_children(n)
1184
+ errf(n, "takes no children") unless n.children.empty?
1185
+ end
1186
+
1187
+ # Checks n's argument count and refuses any property not listed.
1188
+ def only_args(n, args, *props)
1189
+ errf(n, "takes #{args} arguments, got #{n.args.size}") if n.args.size != args
1190
+ n.props.each_key { |key| errf(n, "unknown property #{quote(key)}") unless props.include?(key) }
1191
+ end
1192
+
1193
+ def str(n)
1194
+ no_props(n)
1195
+ no_children(n)
1196
+ if n.args.size != 1 || !n.args[0].string?
1197
+ errf(n, "needs one string")
1198
+ return ""
1199
+ end
1200
+ n.args[0].string
1201
+ end
1202
+
1203
+ def one_of(n, allowed)
1204
+ value = str(n)
1205
+ if !value.empty? && !allowed.include?(value)
1206
+ errf(n, "must be one of #{list_text(allowed)}, got #{quote(value)}")
1207
+ end
1208
+ value
1209
+ end
1210
+
1211
+ # Reads a child that's either bare or holds #true or #false.
1212
+ def flag_value(n)
1213
+ no_props(n)
1214
+ no_children(n)
1215
+ return true if n.args.empty?
1216
+ if n.args.size != 1 || n.args[0].kind != :bool
1217
+ errf(n, "must be #true or #false")
1218
+ return false
1219
+ end
1220
+ n.args[0].bool
1221
+ end
1222
+
1223
+ def color_arg(n)
1224
+ if n.args.size != 1 || !n.args[0].string?
1225
+ errf(n, "needs one color")
1226
+ return ""
1227
+ end
1228
+ palette_color(n, n.args[0].string)
1229
+ end
1230
+
1231
+ # Reads a color list that can leave gaps with `none`.
1232
+ def gap_color_args(n)
1233
+ errf(n, "needs at least one color") if n.args.empty?
1234
+ colors = []
1235
+ n.args.each do |a|
1236
+ if !a.string?
1237
+ errf(n, "colors must be palette names")
1238
+ elsif a.string == NO_COLOR
1239
+ colors << NO_COLOR
1240
+ else
1241
+ colors << palette_color(n, a.string)
1242
+ end
1243
+ end
1244
+ colors
1245
+ end
1246
+
1247
+ def palette_color(n, name)
1248
+ return name if @gradients.key?(name)
1249
+ solid_color(n, name)
1250
+ end
1251
+
1252
+ # For the places a gradient has no meaning.
1253
+ def solid_color(n, name)
1254
+ return name if @palette.key?(name)
1255
+ if @gradients.key?(name) || @gradient_names.include?(name)
1256
+ errf(n, "#{quote(name)} is a gradient, and a solid color is needed here")
1257
+ return name
1258
+ end
1259
+ errf(n, "color #{quote(name)} isn't in the palette")
1260
+ name
1261
+ end
1262
+
1263
+ def number_value(n, v)
1264
+ if v.kind != :number
1265
+ errf(n, "needs a number")
1266
+ return 0.0
1267
+ end
1268
+ unless Limits.in_limits(v.number)
1269
+ errf(n, "needs a finite number of a reasonable size")
1270
+ return 0.0
1271
+ end
1272
+ v.number.to_f
1273
+ end
1274
+
1275
+ def number(n)
1276
+ no_props(n)
1277
+ no_children(n)
1278
+ if n.args.size != 1
1279
+ errf(n, "needs one number")
1280
+ return 0.0
1281
+ end
1282
+ number_value(n, n.args[0])
1283
+ end
1284
+
1285
+ def numbers(n)
1286
+ no_props(n)
1287
+ no_children(n)
1288
+ n.args.map { |v| number_value(n, v) }
1289
+ end
1290
+
1291
+ def positives(n)
1292
+ values = numbers(n)
1293
+ values.each { |v| positive(n, v) }
1294
+ values
1295
+ end
1296
+
1297
+ def positive(n, v)
1298
+ errf(n, "needs a positive number") if v <= 0
1299
+ v
1300
+ end
1301
+
1302
+ # Reads a size that defaults to 0, which can also be written as 0.
1303
+ def not_negative(n, v)
1304
+ errf(n, "can't be negative") if v < 0
1305
+ v
1306
+ end
1307
+
1308
+ def integer(n, v, limit)
1309
+ if v != v.round(half: :even) || v < 1
1310
+ errf(n, "needs a positive whole number")
1311
+ return 0
1312
+ end
1313
+ if v > limit
1314
+ errf(n, "can't be more than #{limit}")
1315
+ return 0
1316
+ end
1317
+ v.to_i
1318
+ end
1319
+
1320
+ def prop(n, key)
1321
+ v = n.prop(key)
1322
+ if v.nil?
1323
+ errf(n, "needs #{key}=")
1324
+ return 0.0
1325
+ end
1326
+ number_value(n, v)
1327
+ end
1328
+
1329
+ def bool_prop(n, key)
1330
+ v = n.prop(key)
1331
+ return false if v.nil?
1332
+ if v.kind != :bool
1333
+ errf(n, "#{key} must be #true or #false")
1334
+ return false
1335
+ end
1336
+ v.bool
1337
+ end
1338
+
1339
+ def path_data(n)
1340
+ d = str(n)
1341
+ unless Numbers.valid_path(d)
1342
+ errf(n, "isn't SVG path data")
1343
+ return ""
1344
+ end
1345
+ d
1346
+ end
1347
+
1348
+ def box_value(n, text)
1349
+ values = Numbers.list(text)
1350
+ if values.nil? || values.size != 4
1351
+ errf(n, "box must be \"x y width height\", with each a finite decimal number of a reasonable size")
1352
+ return [0.0, 0.0, 0.0, 0.0]
1353
+ end
1354
+ values
1355
+ end
1356
+
1357
+ # Reads `edge wavy depth=N period=N` or `edge zigzag depth=N count=N`.
1358
+ def line(n)
1359
+ no_children(n)
1360
+ if n.args.size != 1 || !n.args[0].string? || (n.args[0].string != "wavy" && n.args[0].string != "zigzag")
1361
+ errf(n, "needs a kind: wavy or zigzag")
1362
+ return nil
1363
+ end
1364
+ only_args(n, 1, "depth", "period", "count")
1365
+ l = Model::Line.new
1366
+ l.kind = n.args[0].string
1367
+ l.depth = positive(n, prop(n, "depth"))
1368
+ v = n.prop("period")
1369
+ l.period = positive(n, number_value(n, v)) if v
1370
+ v = n.prop("count")
1371
+ l.count = integer(n, number_value(n, v), Limits::MAX_COPIES) if v
1372
+ if l.period == 0 && l.count == 0
1373
+ errf(n, "needs `period` or `count`")
1374
+ return nil
1375
+ end
1376
+ errf(n, "needs `period` or `count`, not both") if l.period != 0 && l.count != 0
1377
+ l
1378
+ end
1379
+
1380
+ def quarters(n)
1381
+ l = Model::Quarters.new
1382
+ colors = gap_color_args(n)
1383
+ no_props(n)
1384
+ if colors.size != 4
1385
+ errf(n, "needs 4 colors")
1386
+ else
1387
+ l.colors = colors
1388
+ end
1389
+ h = {
1390
+ "diagonal" => ->(c) { l.diagonal = flag_value(c) },
1391
+ "split" => ->(c) { l.split = at(c) }
1392
+ }
1393
+ children(n, ["cut"], with_effects(l, h))
1394
+ errf(n, "`split` only applies to upright quarters") if l.diagonal && l.split
1395
+ l
1396
+ end
1397
+
1398
+ def checks(n)
1399
+ l = Model::Checks.new
1400
+ l.colors = gap_color_args(n)
1401
+ no_props(n)
1402
+ h = {
1403
+ "rows" => ->(c) { l.rows = integer(c, number(c), Limits::MAX_COPIES) },
1404
+ "columns" => ->(c) { l.columns = integer(c, number(c), Limits::MAX_COPIES) },
1405
+ "flow" => ->(c) { l.flow = one_of(c, CHECKS_FLOW) }
1406
+ }
1407
+ children(n, ["cut"], with_effects(l, h))
1408
+ errf(n, "needs at least 2 colors") if l.colors.size < 2
1409
+ errf(n, "needs `rows` and `columns`") if l.rows == 0 || l.columns == 0
1410
+ errf(n, "makes more than #{Limits::MAX_COPIES} cells") if l.rows * l.columns > Limits::MAX_COPIES
1411
+ l
1412
+ end
1413
+
1414
+ def rays(n)
1415
+ l = Model::Rays.new
1416
+ l.colors = gap_color_args(n)
1417
+ no_props(n)
1418
+ count = 0
1419
+ h = {
1420
+ "from" => lambda do |c|
1421
+ if !c.args.empty?
1422
+ l.from = one_of(c, RAY_FROM)
1423
+ else
1424
+ l.at = at(c)
1425
+ end
1426
+ end,
1427
+ "count" => ->(c) { count = integer(c, number(c), Limits::MAX_COPIES) },
1428
+ "ratio" => ->(c) { l.ratio = positives(c) },
1429
+ "rotate" => ->(c) { l.rotate = number(c) },
1430
+ "measure" => ->(c) { l.by_edge = one_of(c, MEASURE) == "edge" }
1431
+ }
1432
+ children(n, ["cut"], with_effects(l, h))
1433
+ if l.by_edge && l.rotate != 0
1434
+ errf(n, "`measure edge` follows the region's edges, so it can't also have a `rotate`")
1435
+ end
1436
+ return l if l.colors.empty?
1437
+ l.colors = cycle(n, l.colors, count)
1438
+ l.ratio = ratio(n, l.ratio, l.colors.size)
1439
+ l
1440
+ end
1441
+
1442
+ # Reads a pile or pall, which are shapes tied to their region's edges.
1443
+ def ordinary_shape(n)
1444
+ l = Model::Charge.new
1445
+ l.shape = Model::Shape.new
1446
+ l.shape.kind = n.name
1447
+ l.color = color_arg(n)
1448
+ no_props(n)
1449
+ h = { "fimbriate" => ->(c) { l.fimbriate = edge(c) } }
1450
+ shape_body(n, l.shape, with_effects(l, h))
1451
+ if l.fimbriate && l.shape.hollow > 0
1452
+ errf(n, "fimbriation edges a filled shape, so it can't go with `hollow` or `lines`")
1453
+ end
1454
+ l
1455
+ end
1456
+
1457
+ def panel(n, depth)
1458
+ l = Model::Panel.new
1459
+ # An `at center` gives no position, but it's still an `at`.
1460
+ placed = false
1461
+ no_values(n)
1462
+ h = {
1463
+ "side" => ->(c) { l.side = one_of(c, FROM) },
1464
+ "corner" => ->(c) { l.corner = one_of(c, CORNER) },
1465
+ "at" => lambda do |c|
1466
+ l.at = at(c)
1467
+ placed = true
1468
+ end,
1469
+ "width" => ->(c) { l.width = positive(c, number(c)) },
1470
+ "fly" => ->(c) { l.fly = positive(c, number(c)) },
1471
+ "hoist" => ->(c) { l.hoist = positive(c, number(c)) },
1472
+ "edge" => ->(c) { l.line = line(c) }
1473
+ }
1474
+ container(n, depth, l, l.layers, h)
1475
+ check_waves(n, l.line)
1476
+ if !l.side.empty? && !l.corner.empty?
1477
+ errf(n, "needs either `side` or `corner`, not both")
1478
+ elsif !l.side.empty?
1479
+ errf(n, "a side panel needs a `width`") if l.width == 0
1480
+ if l.fly != 0 || l.hoist != 0 || placed
1481
+ errf(n, "a side panel takes a `width`, and no `fly`, `hoist` or `at`")
1482
+ end
1483
+ else
1484
+ errf(n, "needs a `side` and `width`, or a `fly` and `hoist`") if l.fly == 0 || l.hoist == 0
1485
+ errf(n, "only a side panel can have an `edge`") if l.line
1486
+ errf(n, "needs either `corner` or `at`, not both") if !l.corner.empty? && placed
1487
+ errf(n, "only a side panel has a `width`") if l.width != 0
1488
+ end
1489
+ errf(n, "needs at least one layer") if l.layers.empty?
1490
+ l
1491
+ end
1492
+
1493
+ def use(n, depth)
1494
+ l = Model::Use.new
1495
+ no_props(n)
1496
+ if n.args.size != 1 || !n.args[0].string?
1497
+ errf(n, "needs the name of a definition")
1498
+ return nil
1499
+ end
1500
+ l.name = n.args[0].string
1501
+ d = @defines[l.name]
1502
+ if d.nil? || d.shape
1503
+ errf(n, "#{quote(l.name)} isn't a defined design")
1504
+ return nil
1505
+ end
1506
+ if depth + d.height > Limits::MAX_DEPTH
1507
+ errf(n, "#{quote(l.name)} nests more than #{Limits::MAX_DEPTH} levels deep where it's used")
1508
+ end
1509
+ l.design = d
1510
+ children(n, ["cut"], with_effects(l, nil))
1511
+ l
1512
+ end
1513
+
1514
+ # Reads a reusable shape or design: `define NAME hoist=H fly=F { ... }`.
1515
+ def define(n)
1516
+ if n.args.size != 1 || !n.args[0].string?
1517
+ errf(n, "needs a name")
1518
+ return
1519
+ end
1520
+ name = n.args[0].string
1521
+ if name.empty?
1522
+ errf(n, "needs a name")
1523
+ return
1524
+ end
1525
+ if @defines.key?(name) || SHAPE_KINDS.include?(name) || name == "svg" || name == "pile" || name == "pall"
1526
+ errf(n, "#{quote(name)} is already taken")
1527
+ return
1528
+ end
1529
+ only_args(n, 1, "hoist", "fly")
1530
+ d = Model::Define.new
1531
+ if n.prop("fly") || n.prop("hoist")
1532
+ d.fly = positive(n, prop(n, "fly"))
1533
+ d.hoist = positive(n, prop(n, "hoist"))
1534
+ end
1535
+ if n.children.empty?
1536
+ errf(n, "needs a shape or layers")
1537
+ return
1538
+ end
1539
+ nodes = n.children
1540
+ if nodes.size == 1 && SHAPE_KINDS.include?(nodes[0].name)
1541
+ c = nodes[0]
1542
+ errf(n, "only a design has its own grid, and a shape takes its size from what uses it") if d.fly != 0
1543
+ s = Model::Shape.new
1544
+ s.kind = c.name
1545
+ if s.kind == "path" && !c.args.empty?
1546
+ # The usual form, `path "M..." box="0 0 10 10"`, puts it all on one line. Its size
1547
+ # comes from each charge using it, so nothing more can be checked yet.
1548
+ s.d, s.box = line_path(c)
1549
+ d.shape = s
1550
+ @defines[name] = d
1551
+ return
1552
+ end
1553
+ no_values(c)
1554
+ shape_body(c, s, nil)
1555
+ d.shape = s
1556
+ @defines[name] = d
1557
+ return
1558
+ end
1559
+ nodes.each do |c|
1560
+ l = layer(c, 2)
1561
+ d.layers << l if l
1562
+ end
1563
+ d.size = Limits.layers_size(d.layers, @longer)
1564
+ d.height = Limits.layers_height(d.layers)
1565
+ @defines[name] = d
1566
+ end
1567
+
1568
+ # Reads the one-line form of a path, `path "M..." box="x y width height"`, which takes nothing
1569
+ # else. Gives [d, box].
1570
+ def line_path(n)
1571
+ only_args(n, 1, "box")
1572
+ no_children(n)
1573
+ d = ""
1574
+ box = [0.0, 0.0, 0.0, 0.0]
1575
+ if n.args.size == 1 && n.args[0].string? && Numbers.valid_path(n.args[0].string)
1576
+ d = n.args[0].string
1577
+ else
1578
+ errf(n, "isn't SVG path data")
1579
+ end
1580
+ b = n.prop("box")
1581
+ box = box_value(n, b.string) if b&.string?
1582
+ errf(n, "needs a `box` with an area") if box[2] <= 0 || box[3] <= 0
1583
+ [d, box]
1584
+ end
1585
+
1586
+ # Reads a flag's silhouette: a polygon or path inside it, or a named form.
1587
+ def outline(n)
1588
+ no_props(n)
1589
+ o = Model::Outline.new
1590
+ args = n.args
1591
+ if args.size > 1 || (args.size == 1 && !args[0].string?)
1592
+ errf(n, "takes a named form, or a polygon or path inside it")
1593
+ return nil
1594
+ end
1595
+ if args.size == 1
1596
+ o.kind = args[0].string
1597
+ case o.kind
1598
+ when "swallowtail", "tongued", "pennant"
1599
+ nil
1600
+ else
1601
+ errf(n, "unknown form #{quote(o.kind)}")
1602
+ return nil
1603
+ end
1604
+ given = {}
1605
+ h = {
1606
+ "depth" => lambda do |c|
1607
+ o.depth = positive(c, number(c))
1608
+ given["depth"] = true
1609
+ end,
1610
+ "tip" => lambda do |c|
1611
+ o.tip = not_negative(c, number(c))
1612
+ given["tip"] = true
1613
+ end,
1614
+ "tongue" => lambda do |c|
1615
+ o.tongue = positive(c, number(c))
1616
+ given["tongue"] = true
1617
+ end,
1618
+ "taper" => lambda do |c|
1619
+ o.taper = not_negative(c, number(c))
1620
+ given["taper"] = true
1621
+ end
1622
+ }
1623
+ children(n, [], h)
1624
+ errf(n, "needs a `depth`") if o.kind != "pennant" && o.depth == 0
1625
+ errf(n, "needs a `tongue`") if o.kind == "tongued" && o.tongue == 0
1626
+ if (given["tip"] && o.kind != "pennant") || (given["tongue"] && o.kind != "tongued") ||
1627
+ (given["taper"] && o.kind != "swallowtail") || (given["depth"] && o.kind == "pennant")
1628
+ errf(n, "has a value that a #{o.kind} doesn't use")
1629
+ end
1630
+ return o
1631
+ end
1632
+ shapes = 0
1633
+ h = {
1634
+ "polygon" => lambda do |c|
1635
+ shapes += 1
1636
+ errf(c, "an outline holds one shape") if shapes > 1
1637
+ s = Model::Shape.new
1638
+ s.kind = "polygon"
1639
+ no_values(c)
1640
+ shape_body(c, s, nil)
1641
+ errf(c, "an outline is a whole shape, so it can't be `hollow`") if s.hollow > 0
1642
+ o.kind = "polygon"
1643
+ o.vertices = s.vertices
1644
+ end,
1645
+ "path" => lambda do |c|
1646
+ shapes += 1
1647
+ errf(c, "an outline holds one shape") if shapes > 1
1648
+ o.kind = "path"
1649
+ o.d, o.box = line_path(c)
1650
+ end
1651
+ }
1652
+ children(n, [], h)
1653
+ if o.kind.empty?
1654
+ errf(n, "needs a form, a `polygon` or a `path`")
1655
+ return nil
1656
+ end
1657
+ o
1658
+ end
1659
+
1660
+ def reverse(n, flag)
1661
+ args = n.args
1662
+ if args.size == 1 && args[0].string? && args[0].string == "mirror"
1663
+ # The default, for saying so outright.
1664
+ no_props(n)
1665
+ no_children(n)
1666
+ return
1667
+ end
1668
+ no_values(n)
1669
+ r = Model::Reverse.new
1670
+ n.children.each do |c|
1671
+ # It holds the flag's layers for that side, so they're at the top level.
1672
+ l = layer(c, 1)
1673
+ r.layers << l if l
1674
+ end
1675
+ errf(n, "needs layers, or `mirror`") if r.layers.empty?
1676
+ count(n, r.layers)
1677
+ flag.reverse = r
1678
+ end
1679
+
1680
+ def adapt(n, flag)
1681
+ no_values(n)
1682
+ a = Model::Adapt.new
1683
+ mode = lambda do |c|
1684
+ next "extend" if c.args.size == 1 && c.args[0].string? && c.args[0].string == "cut"
1685
+ one_of(c, MODE)
1686
+ end
1687
+ h = {
1688
+ "range" => lambda do |c|
1689
+ v = numbers(c)
1690
+ if v.size != 2 || v[0] <= 0 || v[1] < v[0]
1691
+ errf(c, "needs a lowest and highest fly-to-hoist ratio")
1692
+ return
1693
+ end
1694
+ a.min = v[0]
1695
+ a.max = v[1]
1696
+ end,
1697
+ "wider" => ->(c) { a.wider = mode.call(c) },
1698
+ "narrower" => ->(c) { a.narrower = mode.call(c) }
1699
+ }
1700
+ children(n, [], h)
1701
+ errf(n, "needs `wider`, `narrower` or both") if a.wider.empty? && a.narrower.empty?
1702
+ flag.adapt = a
1703
+ end
1704
+
1705
+ def variant(n, flag)
1706
+ if n.args.size != 1 || !n.args[0].string?
1707
+ errf(n, "needs a name")
1708
+ return
1709
+ end
1710
+ no_props(n)
1711
+ name = n.args[0].string
1712
+ if name.empty?
1713
+ errf(n, "needs a name")
1714
+ return
1715
+ end
1716
+ if flag.variants.key?(name)
1717
+ errf(n, "#{quote(name)} is defined twice")
1718
+ return
1719
+ end
1720
+ v = Model::Variant.new
1721
+ settings = {
1722
+ "from" => ->(c) { v.from = one_of(c, VIEW) },
1723
+ "upright" => ->(c) { v.upright = flag_value(c) },
1724
+ "ratio" => ->(c) { v.ratio = positive(c, number(c)) },
1725
+ "proportion" => lambda do |c|
1726
+ only_args(c, 0, "hoist", "fly")
1727
+ v.hoist = positive(c, prop(c, "hoist"))
1728
+ v.fly = positive(c, prop(c, "fly"))
1729
+ no_children(c)
1730
+ end,
1731
+ "outline" => ->(c) { v.outline = outline(c) },
1732
+ "border" => ->(c) { v.border, v.border_outside = border(c) }
1733
+ }
1734
+ seen = {}
1735
+ n.children.each do |c|
1736
+ handler = settings[c.name]
1737
+ if handler.nil?
1738
+ # Its layers replace the flag's, so they're at the top level.
1739
+ l = layer(c, 1)
1740
+ v.layers << l if l
1741
+ next
1742
+ end
1743
+ errf(c, "given more than once") if seen[c.name]
1744
+ seen[c.name] = true
1745
+ handler.call(c)
1746
+ end
1747
+ if seen["proportion"]
1748
+ errf(n, "can't have both `proportion` and `ratio`") if seen["ratio"]
1749
+ errf(n, "with a `proportion` needs its own layers") if v.layers.empty?
1750
+ end
1751
+ if v.outline || v.border || v.fly > 0
1752
+ # What it draws within is its own or the flag's, as it would be when rendered.
1753
+ fly = flag.fly
1754
+ hoist = flag.hoist
1755
+ outline = flag.outline
1756
+ border = flag.border
1757
+ outside = flag.border_outside
1758
+ if v.fly > 0
1759
+ fly = v.fly
1760
+ hoist = v.hoist
1761
+ outline = nil
1762
+ border = nil
1763
+ outside = false
1764
+ end
1765
+ outline = v.outline if v.outline
1766
+ if v.border
1767
+ border = v.border
1768
+ outside = v.border_outside
1769
+ end
1770
+ check_outside(n, outline, fly, hoist, border, outside)
1771
+ end
1772
+ count(n, v.layers)
1773
+ flag.variants[name] = v
1774
+ end
1775
+
1776
+ # Reads a text with any sources for it as children.
1777
+ def reference(n)
1778
+ no_props(n)
1779
+ if n.args.size != 1 || !n.args[0].string?
1780
+ errf(n, "needs one string")
1781
+ return nil
1782
+ end
1783
+ r = Model::Reference.new
1784
+ r.text = n.args[0].string
1785
+ children(n, ["source"], { "source" => str_h { |v| r.sources << v } })
1786
+ r
1787
+ end
1788
+
1789
+ # Reads a named sequence of folds.
1790
+ def fold(n, flag)
1791
+ if n.args.size != 1 || !n.args[0].string?
1792
+ errf(n, "needs a name")
1793
+ return
1794
+ end
1795
+ no_props(n)
1796
+ name = n.args[0].string
1797
+ if name.empty?
1798
+ errf(n, "needs a name")
1799
+ return
1800
+ end
1801
+ if flag.folds.key?(name)
1802
+ errf(n, "#{quote(name)} is defined twice")
1803
+ return
1804
+ end
1805
+ f = Model::Fold.new
1806
+ step = lambda do |c|
1807
+ s = fold_step(c)
1808
+ f.steps << s if s
1809
+ end
1810
+ h = {
1811
+ "description" => str_h { |v| f.description = v },
1812
+ "source" => str_h { |v| f.sources << v },
1813
+ "over" => step,
1814
+ "under" => step,
1815
+ "tuck" => step
1816
+ }
1817
+ children(n, %w[source over under tuck], h)
1818
+ errf(n, "needs at least one step") if f.steps.empty?
1819
+ flag.folds[name] = f
1820
+ end
1821
+
1822
+ # Reads `over along=fly at=5 move=bottom`, or for any line, `over through="a b c d" move="e f"`.
1823
+ def fold_step(n)
1824
+ no_children(n)
1825
+ only_args(n, 0, "along", "at", "move", "through")
1826
+ s = Model::FoldStep.new
1827
+ s.kind = n.name
1828
+ move_value = n.prop("move")
1829
+ if move_value.nil? || !move_value.string?
1830
+ errf(n, "needs move=, the part that moves")
1831
+ return nil
1832
+ end
1833
+ move = move_value.string
1834
+ through = n.prop("through")
1835
+ if through
1836
+ if n.prop("along") || n.prop("at")
1837
+ errf(n, "a crease is `through=` or `along=` and `at=`, not both")
1838
+ return nil
1839
+ end
1840
+ line = point_list(n, through, 4)
1841
+ point = point_list(n, move_value, 2)
1842
+ return nil if line.nil? || point.nil?
1843
+ s.a = Model::Point.new(line[0], line[1])
1844
+ s.b = Model::Point.new(line[2], line[3])
1845
+ s.moving = Model::Point.new(point[0], point[1])
1846
+ s.through = line
1847
+ s.move_to = point
1848
+ return s
1849
+ end
1850
+ along = n.prop("along")
1851
+ if along.nil? || !along.string? || n.prop("at").nil?
1852
+ errf(n, "needs along= and at=, or through=")
1853
+ return nil
1854
+ end
1855
+ at = prop(n, "at")
1856
+ s.along = along.string
1857
+ s.at = at
1858
+ s.move = move
1859
+ case along.string
1860
+ when "fly"
1861
+ s.a = Model::Point.new(0, at)
1862
+ s.b = Model::Point.new(1, at)
1863
+ if move == "top"
1864
+ s.moving = Model::Point.new(0, at - 1)
1865
+ elsif move == "bottom"
1866
+ s.moving = Model::Point.new(0, at + 1)
1867
+ else
1868
+ errf(n, "a crease along the fly moves top or bottom")
1869
+ return nil
1870
+ end
1871
+ when "hoist"
1872
+ s.a = Model::Point.new(at, 0)
1873
+ s.b = Model::Point.new(at, 1)
1874
+ if move == "hoist"
1875
+ s.moving = Model::Point.new(at - 1, 0)
1876
+ elsif move == "fly"
1877
+ s.moving = Model::Point.new(at + 1, 0)
1878
+ else
1879
+ errf(n, "a crease along the hoist moves hoist or fly")
1880
+ return nil
1881
+ end
1882
+ else
1883
+ errf(n, "along must be fly or hoist")
1884
+ return nil
1885
+ end
1886
+ s
1887
+ end
1888
+
1889
+ def point_list(n, v, count)
1890
+ unless v.string?
1891
+ errf(n, "needs #{count} numbers in a string")
1892
+ return nil
1893
+ end
1894
+ values = Numbers.list(v.string)
1895
+ if values.nil? || values.size != count
1896
+ errf(n, "needs #{count} finite decimal numbers of a reasonable size in a string")
1897
+ return nil
1898
+ end
1899
+ values
1900
+ end
1901
+ end
1902
+ end