forked from nicklockwood/ShapeScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStandardLibrary.swift
More file actions
477 lines (455 loc) · 17.1 KB
/
StandardLibrary.swift
File metadata and controls
477 lines (455 loc) · 17.1 KB
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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
//
// StandardLibrary.swift
// ShapeScript
//
// Created by Nick Lockwood on 18/12/2018.
// Copyright © 2018 Nick Lockwood. All rights reserved.
//
import Euclid
import Foundation
#if canImport(SVGPath)
import SVGPath
#endif
extension Dictionary where Key == String, Value == Symbol {
static func + (lhs: Symbols, rhs: Symbols) -> Symbols {
lhs.merging(rhs) { $1 }
}
static let transform: Symbols = [
"position": .property(.vector, { parameter, context in
context.transform.offset = parameter.value as! Vector
}, { context in
.vector(context.transform.offset)
}),
"orientation": .property(.rotation, { parameter, context in
context.transform.rotation = parameter.value as! Rotation
}, { context in
.rotation(context.transform.rotation)
}),
"size": .property(.size, { parameter, context in
context.transform.scale = parameter.value as! Vector
}, { context in
.size(context.transform.scale)
}),
]
static let childTransform: Symbols = [
"translate": .command(.vector) { parameter, context in
let vector = parameter.value as! Vector
context.childTransform.translate(by: vector)
},
"rotate": .command(.rotation) { parameter, context in
let rotation = parameter.value as! Rotation
context.childTransform.rotate(by: rotation)
},
"scale": .command(.size) { parameter, context in
let scale = parameter.value as! Vector
context.childTransform.scale(by: scale)
},
]
static let colors: Symbols = [
"white": .constant(.color(.white)),
"black": .constant(.color(.black)),
"gray": .constant(.color(.gray)),
"grey": .constant(.color(.gray)),
"red": .constant(.color(.red)),
"green": .constant(.color(.green)),
"blue": .constant(.color(.blue)),
"yellow": .constant(.color(.yellow)),
"cyan": .constant(.color(.cyan)),
"magenta": .constant(.color(.magenta)),
"orange": .constant(.color(.orange)),
]
static let color: Symbols = colors + [
"color": .property(.color, { parameter, context in
context.material.color = parameter.colorValue
}, { context in
.color(context.material.color ?? .white)
}),
]
static let material: Symbols = color + [
"opacity": .property(.number, { parameter, context in
context.material.opacity = parameter.doubleValue * context.opacity
}, { context in
.number(context.material.opacity / context.opacity)
}),
"texture": .property(.texture, { parameter, context in
context.material.texture = parameter.value as? Texture
}, { context in
.texture(context.material.texture)
}),
]
static let meshes: Symbols = [
// primitives
"cone": .block(.shape) { context in
.mesh(Geometry(type: .cone(segments: context.detail), in: context))
},
"cylinder": .block(.shape) { context in
.mesh(Geometry(type: .cylinder(segments: context.detail), in: context))
},
"sphere": .block(.shape) { context in
.mesh(Geometry(type: .sphere(segments: context.detail), in: context))
},
"cube": .block(.shape) { context in
.mesh(Geometry(type: .cube, in: context))
},
// container
"group": .block(.group) { context in
.mesh(Geometry(type: .group, in: context))
},
// builders
"extrude": .block(.custom(.builder, ["along": .paths])) { context in
let along = context.value(for: "along")?.tupleValue as? [Path] ?? []
return .mesh(Geometry(type: .extrude(context.paths, along: along), in: context))
},
"lathe": .block(.builder) { context in
.mesh(Geometry(type: .lathe(context.paths, segments: context.detail), in: context))
},
"loft": .block(.builder) { context in
.mesh(Geometry(type: .loft(context.paths), in: context))
},
"fill": .block(.builder) { context in
.mesh(Geometry(type: .fill(context.paths), in: context))
},
// csg
"union": .block(.group) { context in
.mesh(Geometry(type: .union, in: context))
},
"difference": .block(.group) { context in
.mesh(Geometry(type: .difference, in: context))
},
"intersection": .block(.group) { context in
.mesh(Geometry(type: .intersection, in: context))
},
"xor": .block(.group) { context in
.mesh(Geometry(type: .xor, in: context))
},
"stencil": .block(.group) { context in
.mesh(Geometry(type: .stencil, in: context))
},
// lights
"light": .block(.custom(nil, [
"position": .vector,
"orientation": .rotation,
"color": .color,
"spread": .number,
"penumbra": .number,
])) { context in
var hasPosition = false, hasOrientation = false
if let position = context.value(for: "position")?.value as? Vector {
context.transform.offset = position
hasPosition = true
}
if let orientation = context.value(for: "orientation")?.value as? Rotation {
context.transform.rotation = orientation
hasOrientation = true
}
return .mesh(Geometry(
type: .light(Light(
hasPosition: hasPosition,
hasOrientation: hasOrientation,
color: context.value(for: "color")?.colorValue ?? .white,
spread: context.value(for: "spread")?.angleValue ?? (.pi / 4),
penumbra: context.value(for: "penumbra")?.doubleValue ?? 1
)),
in: context
))
},
// debug
"debug": .block(.group) { context in
context.children.forEach {
if case let .mesh(geometry) = $0 {
geometry.debug = true
}
}
if context.children.count == 1,
case let .mesh(child) = context.children[0]
{
return .mesh(child)
}
return .mesh(Geometry(type: .group, in: context))
},
]
static let paths: Symbols = [
"path": .block(.path) { context in
var subpaths = [Path]()
var points = [PathPoint]()
func endPath() {
if !points.isEmpty {
subpaths.append(.curve(points, detail: context.detail / 4))
}
}
for child in context.children {
switch child {
case let .point(point):
points.append(point)
case let .path(path):
endPath()
subpaths.append(path)
case .tuple:
// Special case due to tuple type returning element type
throw RuntimeErrorType.assertionFailure(
"Unexpected child of type tuple in path"
)
default:
throw RuntimeErrorType.assertionFailure(
"Unexpected child of type \(child.type.errorDescription) in path"
)
}
}
endPath()
if subpaths.count != 1 {
subpaths = [Path(subpaths: subpaths)]
}
return .path(subpaths[0].transformed(by: context.transform))
},
"circle": .block(.pathShape) { context in
.path(Path.circle(
segments: context.detail,
color: context.material.color
).transformed(by: context.transform))
},
"square": .block(.pathShape) { context in
.path(Path.square(
color: context.material.color
).transformed(by: context.transform))
},
"polygon": .block(.custom(.pathShape, ["sides": .number])) { context in
let sides = context.value(for: "sides")?.intValue ?? 5
return .path(Path.polygon(
sides: sides,
color: context.material.color
).transformed(by: context.transform))
},
"roundrect": .block(.custom(.pathShape, ["radius": .number])) { context in
let radius = context.value(for: "radius")?.doubleValue ?? 0.25
return .path(Path.roundedRectangle(
width: 1,
height: 1,
radius: radius,
detail: context.detail,
color: context.material.color
).transformed(by: context.transform))
},
"text": .block(.custom(.text, [
"font": .font,
"wrapwidth": .number,
"linespacing": .number,
])) { context in
let width = context.value(for: "wrapwidth")?.doubleValue
let text = context.children.map { $0.textValue }
let paths = Path.text(text, width: width, detail: context.detail / 8)
return .tuple(paths.map { .path($0.transformed(by: context.transform)) })
},
"svgpath": .block(.text) { context in
let text = context.children.map { $0.stringValue }.joined(separator: "\n")
let svgPath: SVGPath
do {
svgPath = try SVGPath(string: text)
} catch let error as SVGError {
throw RuntimeErrorType.assertionFailure(error.message)
}
return .path(Path(
svgPath,
detail: context.detail / 8,
color: context.material.color
).transformed(by: context.transform))
},
]
static let points: Symbols = [
// vertices
"point": .function(.vector) { parameter, context in
.point(.point(
parameter.value as! Vector,
color: context.material.color
))
},
"curve": .function(.vector) { parameter, context in
.point(.curve(
parameter.value as! Vector,
color: context.material.color
))
},
]
static let functions: Symbols = [
// Debug
"print": .command(.tuple) { value, context in
context.debugLog(value.tupleValue)
},
"assert": .command(.boolean) { value, _ in
if !value.boolValue {
throw RuntimeErrorType.assertionFailure("")
}
},
// Logic
"true": .constant(.boolean(true)),
"false": .constant(.boolean(false)),
"not": .function(.boolean) { value, _ in
.boolean(!value.boolValue)
},
// Math
"rnd": .function(.void) { _, context in
.number(context.random.next())
},
"seed": .property(.number, { value, context in
context.random = RandomSequence(seed: value.doubleValue)
}, { context in
.number(Double(context.random.seed))
}),
"round": .function(.number) { value, _ in
.number(value.doubleValue.rounded())
},
"floor": .function(.number) { value, _ in
.number(value.doubleValue.rounded(.down))
},
"ceil": .function(.number) { value, _ in
.number(value.doubleValue.rounded(.up))
},
"max": .function(.pair) { value, _ in
let values = value.value as! [Double]
return .number(values.max()!)
},
"min": .function(.pair) { value, _ in
let values = value.value as! [Double]
return .number(values.min()!)
},
"abs": .function(.number) { value, _ in
.number(value.doubleValue.magnitude)
},
"sqrt": .function(.number) { value, _ in
.number(sqrt(value.doubleValue))
},
"pow": .function(.pair) { value, _ in
let values = value.value as! [Double]
return .number(pow(values[0], values[1]))
},
"cos": .function(.number) { value, _ in
.number(cos(value.doubleValue))
},
"acos": .function(.number) { value, _ in
.number(acos(value.doubleValue))
},
"sin": .function(.number) { value, _ in
.number(sin(value.doubleValue))
},
"asin": .function(.number) { value, _ in
.number(asin(value.doubleValue))
},
"tan": .function(.number) { value, _ in
.number(tan(value.doubleValue))
},
"atan": .function(.number) { value, _ in
.number(atan(value.doubleValue))
},
"atan2": .function(.pair) { value, _ in
let values = value.value as! [Double]
return .number(atan2(values[0], values[1]))
},
"pi": .constant(.number(.pi)),
]
static let global: Symbols = _merge(functions, colors, meshes, paths)
static let node: Symbols = _merge(global, transform, [
"name": .property(.string, { parameter, context in
context.name = parameter.stringValue
}, { context in
.string(context.name)
}),
])
static let font: Symbols = [
"font": .property(.font, { parameter, context in
context.font = parameter.stringValue
}, { context in
.string(context.font)
}),
]
static let detail: Symbols = [
"detail": .property(.number, { parameter, context in
// TODO: throw error if min/max detail level exceeded
context.detail = Swift.max(0, parameter.intValue)
}, { context in
.number(Double(context.detail))
}),
]
static let smoothing: Symbols = [
"smoothing": .property(.number, { parameter, context in
// TODO: find a better way to represent null/auto
let angle = Swift.min(.pi, parameter.angleValue)
context.smoothing = angle < .zero ? nil : angle
}, { context in
context.smoothing.map { .angle($0) } ?? .number(-1)
}),
]
static let root: Symbols = _merge(global, font, detail, smoothing, material, childTransform, [
"camera": .block(.custom(nil, [
"position": .vector,
"orientation": .rotation,
"size": .size,
"background": .colorOrTexture,
"fov": .number,
"width": .number,
"height": .number,
])) { context in
var hasPosition = false, hasOrientation = false, hasScale = false
if let position = context.value(for: "position")?.value as? Vector {
context.transform.offset = position
hasPosition = true
}
if let orientation = context.value(for: "orientation")?.value as? Rotation {
context.transform.rotation = orientation
hasOrientation = true
}
if let size = context.value(for: "size")?.value as? Vector {
context.transform.scale = size
hasScale = true
}
return .mesh(Geometry(
type: .camera(Camera(
hasPosition: hasPosition,
hasOrientation: hasOrientation,
hasScale: hasScale,
background: context.background,
fov: context.value(for: "fov")?.angleValue,
width: context.value(for: "width")?.doubleValue,
height: context.value(for: "height")?.doubleValue
)),
in: context
))
},
"background": .property(.colorOrTexture, { parameter, context in
context.background = MaterialProperty(parameter.value) ?? .color(.clear)
}, { context in
.colorOrTexture(context.background)
}),
])
static let shape: Symbols = _merge(node, detail, smoothing, material)
static let group: Symbols = _merge(shape, childTransform, font)
static let user: Symbols = _merge(shape, font)
static let builder: Symbols = group
static let pathShape: Symbols = _merge(global, transform, detail, color)
static let path: Symbols = _merge(pathShape, childTransform, font, points)
static let definition: Symbols = root
static let all: Symbols = _merge(root, shape, path)
}
extension EvaluationContext {
var paths: [Path] {
children.compactMap { $0.value as? Path }
}
}
extension Geometry {
convenience init(type: GeometryType, in context: EvaluationContext) {
self.init(
type: type,
name: context.name,
transform: context.transform,
material: context.material,
smoothing: context.smoothing,
children: context.children.compactMap { $0.value as? Geometry },
sourceLocation: context.sourceLocation
)
}
}
private func _merge(_ symbols: Symbols...) -> Symbols {
var result = Symbols()
for symbols in symbols {
result.merge(symbols) { $1 }
}
return result
}