forked from nicklockwood/ShapeScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGeometry.swift
More file actions
1175 lines (1093 loc) · 45.1 KB
/
Geometry.swift
File metadata and controls
1175 lines (1093 loc) · 45.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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// Geometry.swift
// ShapeScript Lib
//
// Created by Nick Lockwood on 01/08/2021.
// Copyright © 2021 Nick Lockwood. All rights reserved.
//
import Euclid
import Foundation
public typealias Polygon = Euclid.Polygon
/// Cancellation handler - return true to cancel
public typealias CancellationHandler = () -> Bool
/// Legacy callback type - return false to cancel
public typealias LegacyCallback = () -> Bool
public final class Geometry: Hashable {
public let type: GeometryType
public let name: String?
public let transform: Transform
public let material: Material
public let smoothing: Angle?
public let children: [Geometry]
public let isOpaque: Bool // Computed
private let _overestimatedBounds: Bounds
private let _sourceLocation: (() -> SourceLocation?)?
public private(set) lazy var sourceLocation: SourceLocation? = _sourceLocation?()
public private(set) weak var parent: Geometry?
/// The overestimated Geometry bounds *with* local transform applied
public var overestimatedBounds: Bounds {
_overestimatedBounds.transformed(by: transform)
}
/// The overestimated Geometry bounds *without* the local transform applied
@available(*, deprecated, message: "Use overestimatedBounds instead")
public var bounds: Bounds {
_overestimatedBounds
}
public func hash(into hasher: inout Hasher) {
hasher.combine(type)
hasher.combine(name)
hasher.combine(transform)
hasher.combine(material)
hasher.combine(smoothing)
hasher.combine(children)
}
public static func == (lhs: Geometry, rhs: Geometry) -> Bool {
if lhs === rhs {
return true
}
guard lhs.type == rhs.type,
lhs.name == rhs.name,
lhs.transform == rhs.transform,
lhs.material == rhs.material,
lhs.smoothing == rhs.smoothing,
lhs.children == rhs.children
// Exclude isOpaque, sourceLocation and parent
else {
return false
}
return true
}
/// Whether children should be rendered separately or are included in mesh
public var renderChildren: Bool {
switch type {
case .group:
return true
case .lathe, .intersection, .difference, .stencil, .minkowski:
return false
case .loft, .union, .xor, .extrude, .fill, .hull:
return mesh == nil
case .cone, .cylinder, .sphere, .cube, .path, .mesh, .camera, .light:
return false // These don't have children
}
}
/// Render with debug mode
var debug: Bool {
didSet {
if debug, type == .group {
children.forEach { $0.debug = true }
}
}
}
let cacheKey: GeometryCache.Key
/// The cache used for storing computed meshes
var cache: GeometryCache? {
didSet {
children.forEach { $0.cache = cache }
}
}
private let lock: NSLock = .init()
private var _mesh: Mesh?
/// Returns the pre-built mesh
/// If the mesh has not yet been built, this will return nil
private(set) var mesh: Mesh? {
get {
lock.lock()
defer { lock.unlock() }
return _mesh
}
set {
lock.lock()
defer { lock.unlock() }
_mesh = newValue
_associatedData = nil
}
}
private var _associatedData: Any?
/// External data, e.g. SCNGeometry
var associatedData: Any? {
get {
lock.lock()
defer { lock.unlock() }
if let data = _associatedData {
return data
}
_associatedData = cache?[associatedData: self]
return _associatedData
}
set {
cache?[associatedData: self] = newValue
lock.lock()
defer { lock.unlock() }
_associatedData = newValue
}
}
public init(
type: GeometryType,
name: String?,
transform: Transform,
material: Material,
smoothing: Angle?,
children: [Geometry],
sourceLocation: (() -> SourceLocation?)?,
debug: Bool = false
) {
var material = material
var useMaterialForCache = false
var children = children
var type = type
switch type {
case var .extrude(paths, options):
switch (paths.count, options.along.count) {
case (0, 0):
break
case (1, 0):
(paths, material) = paths.vertexColorsToMaterial(material: material)
type = .extrude(paths, options)
case (1, 1):
var pair = (paths + options.along)
(pair, material) = pair.vertexColorsToMaterial(material: material)
options.along = [pair[1]]
type = .extrude([pair[0]], options)
case (_, 0):
type = .extrude([], .default)
children = paths.map { path in
let (temp, material) = path.vertexColorsToMaterial(material: material)
let (path, offset) = temp.withNormalizedPosition()
return Geometry(
type: .extrude([path], options),
name: nil,
transform: .translation(offset),
material: material,
smoothing: smoothing,
children: [],
sourceLocation: sourceLocation
)
}
material = children.first?.material ?? .default
default:
// For extrusions with multiple paths, convert each path to a
// separate child geometry so they can be renderered individually
type = .extrude([], .default)
children = paths.flatMap { path in
options.along.map { along in
let (along, offset) = along.withNormalizedPosition()
let (pair, material) = [path, along].vertexColorsToMaterial(material: material)
var options = options
options.along = [pair[1]]
return Geometry(
type: .extrude([pair[0]], options),
name: nil,
transform: .translation(offset),
material: material,
smoothing: smoothing,
children: [],
sourceLocation: sourceLocation
)
}
}
material = children.first?.material ?? .default
}
case .lathe(var paths, let segments):
switch paths.count {
case 0:
break
case 1:
(paths, material) = paths.vertexColorsToMaterial(material: material)
type = .lathe(paths, segments: segments)
default:
// For lathes with multiple paths, convert each path to a
// separate child geometry so they can be renderered individually
type = .lathe([], segments: 0)
children = paths.map { path in
// TODO: normalize path y-position for better caching
let (path, material) = path.vertexColorsToMaterial(material: material)
return Geometry(
type: .lathe([path], segments: segments),
name: nil,
transform: .identity,
material: material,
smoothing: smoothing,
children: [],
sourceLocation: sourceLocation
)
}
material = children.first?.material ?? .default
}
case var .fill(paths):
switch paths.count {
case 0:
break
case 1:
(paths, material) = paths.vertexColorsToMaterial(material: material)
type = .fill(paths)
default:
// For fills with multiple paths, convert each path to a
// separate child geometry so they can be renderered individually
type = .fill([])
children = paths.map { path in
let (temp, material) = path.vertexColorsToMaterial(material: material)
let (path, offset) = temp.withNormalizedPosition()
return Geometry(
type: .fill([path]),
name: nil,
transform: .translation(offset),
material: material,
smoothing: smoothing,
children: [],
sourceLocation: sourceLocation
)
}
material = children.first?.material ?? .default
}
case var .loft(paths):
// TODO: normalize all paths by their collective offset for better caching
(paths, material) = paths.vertexColorsToMaterial(material: material)
type = .loft(paths)
case var .path(path):
(path, material) = path.vertexColorsToMaterial(material: material)
type = .path(path)
case let .mesh(mesh) where !mesh.isEmpty:
material = mesh.materials.first as? Material ?? .default
case .hull, .minkowski:
useMaterialForCache = true
case .union, .xor, .difference, .intersection, .stencil, .mesh:
material = children.first?.material ?? .default
case .group:
if debug {
children.forEach { $0.debug = true }
}
case .cone, .cylinder, .sphere, .cube, .camera, .light:
break
}
self.type = type
self.name = name.flatMap { $0.isEmpty ? nil : $0 }
self.transform = transform
self.material = material
self.smoothing = smoothing
self.children = children
self._sourceLocation = sourceLocation
self.debug = debug
var hasVariedMaterials = false
var isOpaque = material.isOpaque
func flattenedCacheKey(for geometry: Geometry) -> GeometryCache.Key {
isOpaque = isOpaque && geometry.material.isOpaque
if !hasVariedMaterials, geometry.material != material {
hasVariedMaterials = true
}
return GeometryCache.Key(
type: geometry.type,
material: geometry.material == material ? nil : geometry.material,
smoothing: geometry.smoothing,
transform: geometry.transform,
flipped: geometry.transform.isFlipped,
children: geometry.children.map(flattenedCacheKey)
)
}
let childKeys = type.isLeafGeometry ? [] : children.map(flattenedCacheKey)
// Must be set after child keys are generated
self.isOpaque = isOpaque
self.cacheKey = .init(
type: type,
material: useMaterialForCache && hasVariedMaterials ? material : nil,
smoothing: smoothing,
transform: .identity,
flipped: transform.isFlipped,
children: childKeys
)
// Compute the overestimated, non-transformed bounds
switch type {
case .difference, .stencil:
self._overestimatedBounds = children.first.map(\.overestimatedBounds) ?? .empty
case .intersection:
self._overestimatedBounds = children.dropFirst().reduce(children.first?.overestimatedBounds ?? .empty) {
$0.intersection($1.overestimatedBounds)
}
case .union, .xor, .group:
self._overestimatedBounds = Bounds(children.map(\.overestimatedBounds))
case .lathe, .fill, .extrude, .loft, .mesh, .hull:
self._overestimatedBounds = type.bounds.union(Bounds(children.map(\.overestimatedBounds)))
case .minkowski:
self._overestimatedBounds = children.reduce(.empty) {
$0.minkowskiSum(with: $1.overestimatedBounds)
}
case .cone, .cylinder, .sphere, .cube, .path:
self._overestimatedBounds = type.bounds
case .camera, .light:
self._overestimatedBounds = .empty
}
// Must be set after all other properties
children.forEach { $0.parent = self }
}
}
public extension Geometry {
/// Geometry and its children produce no output
var isEmpty: Bool {
type.isEmpty && children.allSatisfy(\.isEmpty)
}
/// The camera (if geometry is a camera)
var camera: Camera? {
guard case let .camera(camera) = type else {
return nil
}
return camera
}
/// The light (if geometry is a light)
var light: Light? {
guard case let .light(light) = type else {
return nil
}
return light
}
/// The path (if geometry is a path)
var path: Path? {
guard case let .path(path) = type else {
return nil
}
return path
}
/// The absolute geometry transform relative to the world/scene
var worldTransform: Transform {
(parent?.worldTransform ?? .identity) * transform
}
/// Returns `true` if the geometry's' children should be rendered in debug mode
var childDebug: Bool {
debug || children.contains(where: \.childDebug)
}
/// Return a copy of the geometry with the specified transform applied
func transformed(by transform: Transform) -> Geometry {
Geometry(
type: type,
name: name,
transform: self.transform * transform,
material: material,
smoothing: smoothing,
children: children,
sourceLocation: _sourceLocation,
debug: debug
)
}
@available(*, deprecated, message: "Do not use")
func hasUniformMaterial(_: Material? = nil) -> Bool {
true
}
/// Return a copy of the geometry with the specified properties updated
/// - Note: transform is replaced and not combined like with `transformed(by:)`,
func with(
transform: Transform,
material: Material?,
smoothing: Angle?,
sourceLocation: @escaping () -> SourceLocation?
) -> Geometry {
_with(
name: nil,
transform: transform,
material: material,
smoothing: smoothing,
sourceLocation: sourceLocation,
removingLights: false,
removingGroupTransform: false
)
}
/// Returns a copy of the geometry with light nodes removed
func withoutLights() -> Geometry {
_with(
name: nil,
transform: nil,
material: nil,
smoothing: nil,
sourceLocation: nil,
removingLights: true,
removingGroupTransform: false
)
}
/// Returns a copy of the geometry with group transforms transferred to their children
func withoutGroupTransform() -> Geometry {
_with(
name: nil,
transform: nil,
material: nil,
smoothing: nil,
sourceLocation: nil,
removingLights: false,
removingGroupTransform: true
)
}
/// Builds the meshes for the receiver and all its descendents
/// Built meshes will be stored in the cache. Already-cached meshes will be re-used if available
/// - Returns: false if cancelled or true when completed
func build(_ callback: @escaping LegacyCallback) -> Bool {
buildLeaves(callback) && buildPreview(callback) && buildFinal(callback)
}
/// Returns the union mesh of the receiver and all its descendents
/// The cache is neither checked nor updated. Only already-built meshes are returned.
/// - Note: Includes both material and transform
func flattened(_ callback: @escaping LegacyCallback = { true }) -> Mesh {
flattened(with: material, callback)
}
/// Returns the meshes of the receiver and all its descendents
/// The cache is neither checked nor updated. Only already-built meshes are returned
/// - Note: Includes both material and transform
func meshes(_ callback: @escaping LegacyCallback = { true }) -> [Mesh] {
meshes(with: material, callback)
}
/// Returns the combined mesh of the receiver and all its descendents
/// The cache is neither checked nor updated. Only already-built meshes are returned
/// - Note: Includes both material and transform
func merged(_ callback: @escaping LegacyCallback = { true }) -> Mesh {
var result = mesh ?? .empty
if type.isLeafGeometry {
result = result.merge(mergedChildren(callback))
}
return result
.replacing(nil, with: material)
.transformed(by: transform)
}
}
extension Geometry {
/// Gathers all the named descendents of the receiver (including itself, potentially) into a dictionary
func gatherNamedObjects(_ dictionary: inout [String: Geometry]) {
if let name {
dictionary[name] = self
}
children.forEach { $0.gatherNamedObjects(&dictionary) }
}
}
private extension Collection<Geometry> {
/// Computes the union of the geometries in the collection and all their descendents
/// The cache is neither checked nor updated. Only already-built meshes are included in the union result
/// - Note: Results include both material (if specified) and transform
func flattened(with material: Material?, _ callback: @escaping LegacyCallback) -> [Mesh] {
compactMap { callback() ? $0.flattened(with: material, callback) : nil }
}
/// Returns the meshes of the geometries in the collection and all their descendents
/// The cache is neither checked nor updated. Only already-built meshes are returned
/// - Note: Results include both material (if specified) and transform
func meshes(with material: Material?, _ callback: @escaping LegacyCallback) -> [Mesh] {
flatMap { callback() ? $0.meshes(with: material, callback) : [] }
}
/// Returns a merged mesh for all of the geometries in the collection and all their descendents
/// The cache is neither checked nor updated. Only already-built meshes are returned
/// - Note: Results include both material and transform
func merged(_ callback: @escaping LegacyCallback) -> Mesh {
var result = Mesh.empty
for child in self where callback() {
result = result.merge(child.merged(callback))
}
return result
}
}
private extension Geometry {
/// Computes the union of the meshes of the descendents of the receiver
/// The cache is neither checked nor updated. Only already-built meshes are included in the union result
/// - Note: Includes the receiver's material but not its transform
func flattenedChildren(_ callback: @escaping LegacyCallback) -> [Mesh] {
children.flattened(with: material, callback)
}
/// Returns a merged mesh for all of the descendents of the receiver
/// The cache is neither checked nor updated. Only already-built meshes are returned
/// - Note: Does not include the material or transform of the receiver
func mergedChildren(_ callback: @escaping LegacyCallback) -> Mesh {
children.merged(callback)
}
/// Computes the union of the meshes of the first child of the receiver
/// The cache is neither checked nor updated. Only already-built meshes are included in the union result
/// - Note: Includes the receiver's material but not its transform
func flattenedFirstChild(_ callback: @escaping LegacyCallback) -> Mesh {
children.first.map { $0.flattened(with: self.material, callback) } ?? .empty
}
/// Returns the meshes of the receivers children and their descendents
/// The cache is neither checked nor updated. Only already-built meshes are returned
/// - Note: Includes the receiver's material but not its transform
func childMeshes(_ callback: @escaping () -> Bool) -> [Mesh] {
children.meshes(with: material, callback)
}
/// Computes the union of the meshes of the receiver and all its descendents
/// The cache is neither checked nor updated. Only already-built meshes are included in the union result
/// - Note: Includes material (if specified) and the receiver's transform
func flattened(with material: Material?, _ callback: @escaping LegacyCallback) -> Mesh {
.union(meshes(with: material, callback), isCancelled: { !callback() })
}
/// Returns the meshes of the receiver and all its descendents
/// The cache is neither checked nor updated. Only already-built meshes are returned
/// - Note: Includes both material (if specified) and transform
func meshes(with material: Material?, _ callback: @escaping LegacyCallback) -> [Mesh] {
var meshes = [Mesh]()
if let mesh, mesh != .empty {
meshes.append(mesh)
}
if type.isLeafGeometry {
meshes += childMeshes(callback)
}
return meshes.map {
let mesh = $0.transformed(by: transform)
if material != self.material {
return mesh.replacing(nil, with: self.material)
}
return mesh
}
}
/// Build all geometries that don't have dependencies
/// - Returns: false if cancelled or true when completed
func buildLeaves(_ callback: @escaping LegacyCallback) -> Bool {
if type.isLeafGeometry, !buildMesh(callback) {
return false
}
// TODO: improve isLeafGeometry logic to get rid of this special case
if case .mesh = type, children.isEmpty {
return buildMesh(callback)
}
for child in children where !child.buildLeaves(callback) {
return false
}
return true
}
/// With leaves built, do a rough preview
/// - Returns: false if cancelled or true when completed
func buildPreview(_ callback: @escaping LegacyCallback) -> Bool {
for child in children where !child.buildPreview(callback) {
return false
}
if let mesh = cache?[mesh: self] {
self.mesh = mesh
return callback()
}
switch type {
case .extrude([], _), .lathe([], _), .fill([]):
mesh = nil
case .mesh:
mesh = children.merged(callback) // TODO: not really sure what to do here
case .group, .path,
.cone, .cylinder, .sphere, .cube,
.extrude, .lathe, .loft, .fill:
assert(type.isLeafGeometry) // Leaves
case .stencil, .difference:
mesh = children.first?.merged(callback)
case .union, .xor, .intersection, .hull, .minkowski, .camera, .light:
mesh = nil
}
return callback()
}
/// Builds and caches the final mesh for the receiver and all its descendents
/// - Returns: false if cancelled or true when completed
func buildFinal(_ callback: @escaping LegacyCallback) -> Bool {
for child in children where !child.buildFinal(callback) {
return false
}
if !type.isLeafGeometry {
return buildMesh(callback)
}
return callback()
}
/// Builds and caches the mesh for the receiver. Already-cached mesh will be re-used if available
/// - Note: Child meshes should have already been built before calling (unchecked)
/// - Returns: false if cancelled or true when completed
func buildMesh(_ callback: @escaping LegacyCallback) -> Bool {
if let mesh = cache?[mesh: self] {
self.mesh = mesh
return callback()
}
let isCancelled = { !callback() }
if isCancelled() {
return false
}
switch type {
case .group, .path, .camera, .light:
mesh = .empty
case let .cone(segments):
mesh = .cone(slices: segments)
case let .cylinder(segments):
mesh = .cylinder(slices: segments)
case let .sphere(segments):
mesh = .sphere(slices: segments, stacks: segments / 2)
case .cube:
mesh = .cube()
case let .extrude(paths, .default) where paths.count == 1:
mesh = .extrude(paths[0], isCancelled: isCancelled)
if paths[0].subpaths.count > 1 {
mesh = mesh?.makeWatertight().detessellate()
}
case let .extrude(paths, options) where paths.count == 1 && options.along.count == 1:
mesh = .extrude(
paths[0].materialToVertexColors(material: material),
along: options.along[0].materialToVertexColors(material: material).predividedBy(material),
twist: options.twist,
align: options.align,
isCancelled: isCancelled
).vertexColorsToMaterial(material: material).replacing(material, with: nil)
if !options.along[0].isClosed, paths[0].subpaths.count > 1 {
mesh = mesh?.makeWatertight().detessellate()
}
case let .lathe(paths, segments: segments) where paths.count == 1:
mesh = .lathe(paths[0], slices: segments, isCancelled: isCancelled)
case let .fill(paths) where paths.count == 1:
mesh = .fill(paths[0], isCancelled: isCancelled)
if paths[0].subpaths.count > 1 {
// No point calling makeWatertight() as it doesn't work with double-sided polys
mesh = mesh?.detessellate()
}
case let .loft(paths):
mesh = .loft(paths, isCancelled: isCancelled)
if paths.first != paths.last, paths[0].subpaths.count > 1 || paths.last!.subpaths.count > 1 {
mesh = mesh?.makeWatertight().detessellate()
}
case let .hull(vertices):
let base = Mesh.convexHull(of: vertices, material: material, isCancelled: isCancelled)
let meshes = ([base] + childMeshes(callback)).map { $0.materialToVertexColors(material: material) }
mesh = .convexHull(of: meshes, isCancelled: isCancelled)
.vertexColorsToMaterial(material: material)
.replacing(material, with: nil)
.detessellate()
case .minkowski:
var children = ArraySlice(children.enumerated().sorted {
switch ($0.1.type, $1.1.type) {
case let (.path(a), .path(b)):
// Put closed paths before open paths
if a.isClosed != b.isClosed {
return a.isClosed
}
// TODO: put convex paths before concave paths
// Put smaller paths before larger paths
return a.bounds.size < b.bounds.size
case (.path, _):
// Put meshes before paths
return false
case (_, .path):
return true
case (_, _):
// TODO: put convex meshes before concave meshes
// TODO: put smaller meshes before larger meshes
// Preserve original order
return $0.0 < $1.0
}
}.map { $1 })
guard let first = children.popFirst() else {
mesh = .empty
break
}
var sum: Mesh
if let shape = first.path?.transformed(by: first.transform) {
guard let next = children.popFirst() else {
mesh = .empty
break
}
let shape = shape.materialToVertexColors(material: first.material)
if let path = next.path?.transformed(by: next.transform) {
sum = .fill(shape).minkowskiSum(
with: path.materialToVertexColors(material: next.material),
isCancelled: isCancelled
)
} else {
sum = next.flattened(callback).materialToVertexColors(material: next.material)
.minkowskiSum(with: shape, isCancelled: isCancelled)
}
} else {
sum = first.flattened(callback).materialToVertexColors(material: first.material)
}
while let next = children.popFirst() {
if let path = next.path?.transformed(by: next.transform) {
sum = sum.minkowskiSum(
with: path.materialToVertexColors(material: next.material).predividedBy(first.material),
isCancelled: isCancelled
)
} else {
sum = sum.minkowskiSum(
with: next.flattened(callback).materialToVertexColors(material: next.material),
isCancelled: isCancelled
)
}
}
mesh = sum.vertexColorsToMaterial(material: material).replacing(material, with: nil).detessellate()
case .union, .lathe, .extrude, .fill:
mesh = .union(childMeshes(callback), isCancelled: isCancelled)
case .xor:
mesh = .symmetricDifference(flattenedChildren(callback), isCancelled: isCancelled)
case .difference:
let first = flattenedFirstChild(callback)
let meshes = [first] + children.dropFirst().meshes(with: material, callback)
mesh = .difference(meshes, isCancelled: isCancelled)
case .intersection:
let meshes = flattenedChildren(callback)
mesh = .intersection(meshes, isCancelled: isCancelled)
case .stencil:
let first = flattenedFirstChild(callback)
let meshes = [first] + children.dropFirst().meshes(with: material, callback)
mesh = .stencil(meshes, isCancelled: isCancelled)
case let .mesh(mesh):
self.mesh = .merge([mesh] + childMeshes(callback))
}
if callback() {
mesh = mesh?.makeWatertight()
if let smoothing {
mesh = mesh?.smoothingNormals(forAnglesGreaterThan: smoothing)
}
cache?[mesh: self] = mesh
return true
}
return false
}
func _with(
name: String?,
transform: Transform?,
material: Material?,
smoothing: Angle?,
sourceLocation: (() -> SourceLocation?)?,
removingLights: Bool,
removingGroupTransform: Bool
) -> Geometry {
var type = type
if removingLights, case .light = type {
preconditionFailure()
}
var m = self.material
if let material, case let .mesh(mesh) = type {
if m.opacity?.opacity ?? 1 == 1 {
m.opacity = material.opacity
} else if material.opacity?.color != nil {
let opacity = material.opacity?.opacity ?? 1
switch m.opacity ?? .color(.white) {
case let .color(color):
let opacity = color.a * opacity
m.opacity = .color(.init(opacity, opacity))
case let .texture(texture):
// Since user cannot specify texture opacity, this should always be 1
let opacity = texture.intensity * opacity
m.opacity = .texture(texture.withIntensity(opacity))
}
}
m.albedo = material.albedo ?? m.albedo
m.glow = material.glow ?? m.glow
m.metallicity = material.metallicity ?? m.metallicity
m.roughness = material.roughness ?? m.roughness
// Note: this only replaces the mesh base material, not merged mesh materials
type = .mesh(mesh.replacing(self.material, with: m))
}
var transform = transform.map { self.transform * $0 } ?? self.transform
var childTransform = Transform.identity
if case .group = type, removingGroupTransform {
childTransform = transform
transform = .identity
}
let copy = Geometry(
type: type,
name: name ?? self.name,
transform: transform,
material: m,
smoothing: smoothing ?? self.smoothing,
children: children.compactMap {
if case .light = $0.type, removingLights {
return nil
}
return $0._with(
name: nil,
transform: childTransform,
material: material,
smoothing: nil,
sourceLocation: sourceLocation,
removingLights: removingLights,
removingGroupTransform: removingGroupTransform
)
},
sourceLocation: _sourceLocation ?? sourceLocation,
debug: debug
)
copy.mesh = mesh
return copy
}
}
private extension Color {
func predividedBy(_ other: Color) -> Color {
.init(
other.r > 0 ? r / other.r : r,
other.g > 0 ? g / other.g : g,
other.b > 0 ? b / other.b : b,
other.a > 0 ? a / other.a : a
)
}
}
private extension Material {
func predividedBy(_ other: Material) -> Material {
var result = self
result.albedo = .color({
let lhs = color ?? .white
let rhs = other.color ?? .white
return lhs.predividedBy(rhs)
}())
return result
}
}
private extension [Path] {
/// Returns the uniform color of all vertices, or nil if they have different colors
var uniformVertexColor: Color? {
let uniformColor = first?.uniformVertexColor ?? .white
return allSatisfy { [uniformColor, .white].contains($0.uniformVertexColor) } ? uniformColor : nil
}
/// Convert uniform point colors to a material instead
func vertexColorsToMaterial(material: Material) -> ([Path], Material) {
guard material.texture == nil else {
return (self, material)
}
if let uniformVertexColor {
if uniformVertexColor == .white {
return (self, material)
}
var material = material
material.albedo = .color(uniformVertexColor)
return (map { $0.withColor(nil) }, material)
}
var material = material
material.albedo = .color(.white)
return (self, material)
}
}
extension Path {
/// Returns the uniform color of all vertices, or nil if they have different colors
var uniformVertexColor: Color? {
let uniformColor = points.first?.color ?? .white
return points.allSatisfy { $0.color ?? .white == uniformColor } ? uniformColor : nil
}
/// Convert uniform point colors to a material instead
func vertexColorsToMaterial(material: Material) -> (Path, Material) {
guard material.texture == nil else {
return (self, material)
}
if let uniformVertexColor {
if uniformVertexColor == .white {
return (self, material)
}
var material = material
material.albedo = .color(uniformVertexColor)
return (withColor(nil), material)
}
var material = material
material.albedo = .color(.white)
return (self, material)
}
/// Convert material color to vertex colors, preserving the existing vertex colors if set
func materialToVertexColors(material: ShapeScript.Material?) -> Path {
guard let color = material?.color, color != .white, !hasColors else {
return self
}
return withColor(color)
}
func predividedBy(_ other: Material) -> Path {
mapColors { $0?.predividedBy(other.color ?? .white) }
}
}
extension Polygon {
/// Returns the uniform color of all vertices, or nil if they have different colors
var uniformVertexColor: Color? {
let uniformColor = vertices.first?.color ?? .white
return vertices.allSatisfy { $0.color == uniformColor } ? uniformColor : nil
}
/// Convert uniform vertex colors to a material instead
func vertexColorsToMaterial(material: ShapeScript.Material) -> Polygon {
var material = self.material as? ShapeScript.Material ?? material
guard material.texture == nil else {
return withMaterial(material)
}
if let uniformVertexColor {
if uniformVertexColor == .white {
return withMaterial(material)
}
var material = material
material.albedo = .color(uniformVertexColor)
return withoutVertexColors().withMaterial(material)
}
material.albedo = .color(.white)
return withMaterial(material)
}
/// Convert material colors to vertex colors, preserving the existing vertex colors if set
func materialToVertexColors(material: ShapeScript.Material?) -> Polygon {
guard var material = self.material as? ShapeScript.Material ?? material,
let color = material.color, color != .white,
!hasVertexColors
else {
return self
}
material.albedo = .color(.white)
return mapVertexColors { _ in color }.withMaterial(material)
}
}
extension Mesh {
/// Returns the uniform color of all vertices, or nil if they have different colors
var uniformVertexColor: Color? {
let uniformColor = polygons.first?.uniformVertexColor ?? .white
return polygons.allSatisfy { $0.uniformVertexColor == uniformColor } ? uniformColor : nil
}
/// Convert uniform vertex colors to a material instead
func vertexColorsToMaterial(material: ShapeScript.Material) -> Mesh {
guard material.texture == nil else {
return withMaterial(material)
}
if let uniformVertexColor {
if uniformVertexColor == .white {
return withMaterial(material)
}
var material = material
material.albedo = .color(uniformVertexColor)
return withoutVertexColors().withMaterial(material)
}
var material = material
material.albedo = .color(.white)
return withMaterial(material)
}