-
-
Notifications
You must be signed in to change notification settings - Fork 292
/
conversions.jl
1815 lines (1543 loc) · 78 KB
/
conversions.jl
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
################################################################################
# Type Conversions #
################################################################################
const RangeLike = Union{AbstractVector,ClosedInterval,Tuple{Real,Real}}
function convert_arguments(CT::ConversionTrait, args...)
expanded = expand_dimensions(CT, args...)
if !isnothing(expanded)
return convert_arguments(CT, expanded...)
end
return args
end
function convert_arguments(T::Type{<:AbstractPlot}, args...; kw...)
# landing here means, that there is no matching `convert_arguments` method for the plot type
# Meaning, it needs to be a conversion trait, or it needs single_convert_arguments or expand_dimensions
CT = conversion_trait(T, args...)
# Try to expand dimensions first, as this is the most basic step!
expanded = expand_dimensions(CT, args...)
!isnothing(expanded) && return convert_arguments(T, expanded...; kw...)
# Try single argument convert after
arguments_converted = map(convert_single_argument, args)
if arguments_converted !== args
# This changed something, so we start back with convert_arguments
return convert_arguments(T, arguments_converted...; kw...)
end
# next we try to convert the arguments with the conversion trait
trait_converted = convert_arguments(CT, args...; kw...)
trait_converted !== args && return convert_arguments(T, trait_converted...; kw...)
# else we give up!
return args
end
################################################################################
# Single Argument Conversion #
################################################################################
# if no specific conversion is defined, we don't convert
convert_single_argument(@nospecialize(x)) = x
# replace missings with NaNs
function convert_single_argument(a::AbstractArray{<:Union{Missing, <:Real}})
return float_convert(a)
end
# same for points
function convert_single_argument(a::AbstractArray{<:Union{Missing, <:Point{N, PT}}}) where {N, PT}
T = float_type(PT)
return Point{N,T}[ismissing(x) ? Point{N,T}(NaN) : Point{N,T}(x) for x in a]
end
convert_single_argument(a::AbstractArray{Any}) = convert_single_argument([x for x in a])
# Leave concretely typed vectors alone (AbstractArray{<:Union{Missing, <:Real}} also dispatches for `Vector{Float32}`)
convert_single_argument(a::AbstractArray{T}) where {T<:Real} = a
convert_single_argument(a::AbstractArray{<:Point{N, T}}) where {N, T} = a
################################################################################
# PointBased #
################################################################################
"""
Wrap a single point or equivalent object in a single-element array.
"""
function convert_arguments(::PointBased, x::Real, y::Real)
T = float_type(x, y)
return ([Point{2, T}(x, y)],)
end
function convert_arguments(::PointBased, x::Real, y::Real, z::Real)
T = float_type(x, y, z)
return ([Point{3, T}(x, y, z)],)
end
function convert_arguments(::PointBased, position::VecTypes{N, T}) where {N, T <: Real}
return ([Point{N,float_type(T)}(position)],)
end
function convert_arguments(::PointBased, positions::AbstractVector{<: VecTypes{N, T}}) where {N, T <: Real}
# VecTypes{N, T} will have T undefined if tuple has different number types
_T = @isdefined(T) ? T : Float64
if !(N in (2, 3))
throw(ArgumentError("Only 2D and 3D points are supported."))
end
return (elconvert(Point{N, float_type(_T)}, positions),)
end
function convert_arguments(::PointBased, positions::SubArray{<: VecTypes, 1})
# TODO figure out a good subarray solution
(positions,)
end
"""
Enables to use scatter like a surface plot with x::Vector, y::Vector, z::Matrix
spanning z over the grid spanned by x y
"""
function convert_arguments(::PointBased, x::RealArray, y::RealVector, z::RealMatrix)
T = float_type(x, y, z)
(vec(Point{3, T}.(x, y', z)),)
end
function convert_arguments(::PointBased, x::RealVector, y::RealVector, z::RealVector)
T = float_type(x, y, z)
return (Point{3,T}.(x, y, z),)
end
function convert_arguments(p::PointBased, x::AbstractInterval, y::AbstractInterval, z::RealMatrix)
return convert_arguments(p, to_linspace(x, size(z, 1)), to_linspace(y, size(z, 2)), z)
end
"""
convert_arguments(P, x, y, z)::(Vector)
Takes vectors `x`, `y`, and `z` and turns it into a vector of 3D points of the values
from `x`, `y`, and `z`.
`P` is the plot Type (it is optional).
"""
function convert_arguments(::PointBased, x::RealArray, y::RealMatrix, z::RealMatrix)
T = float_type(x, y, z)
(vec(Point{3, T}.(x, y, z)),)
end
function convert_arguments(::PointBased, x::RealVector, y::RealVector)
return (Point{2,float_type(x, y)}.(x, y),)
end
"""
convert_arguments(P, x)::(Vector)
Takes an input GeometryPrimitive `x` and decomposes it to points.
`P` is the plot Type (it is optional).
"""
function convert_arguments(p::PointBased, x::GeometryPrimitive{Dim, T}) where {Dim, T}
return convert_arguments(p, decompose(Point{Dim, float_type(T)}, x))
end
function convert_arguments(::PointBased, pos::RealMatrix)
(to_vertices(pos),)
end
"""
convert_arguments(P, x, y)::(Vector)
Takes vectors `x` and `y` and turns it into a vector of 2D points of the values
from `x` and `y`.
`P` is the plot Type (it is optional).
"""
convert_arguments(P::PointBased, x::ClosedInterval, y::RealVector) = convert_arguments(P, LinRange(extrema(x)..., length(y)), y)
convert_arguments(P::PointBased, x::RealVector, y::ClosedInterval) = convert_arguments(P, x, LinRange(extrema(y)..., length(x)))
"""
convert_arguments(P, x)::(Vector)
Takes an input `Rect` `x` and decomposes it to points.
`P` is the plot Type (it is optional).
"""
function convert_arguments(P::PointBased, x::Rect2{T}) where T
# TODO fix the order of decompose
return convert_arguments(P, decompose(Point2{float_type(T)}, x)[[1, 2, 4, 3]])
end
function convert_arguments(P::PointBased, mesh::AbstractMesh)
return convert_arguments(P, coordinates(mesh))
end
function convert_arguments(PB::PointBased, linesegments::FaceView{<:Line, P}) where {P<:AbstractPoint}
# TODO FaceView should be natively supported by backends!
return convert_arguments(PB, collect(reinterpret(P, linesegments)))
end
function convert_arguments(::PointBased, rect::Rect3{T}) where {T}
return (decompose(Point3{float_type(T)}, rect),)
end
function convert_arguments(P::Type{<: LineSegments}, rect::Rect3{T}) where {T}
f = decompose(LineFace{Int}, rect)
p = connect(decompose(Point3{float_type(T)}, rect), f)
return convert_arguments(P, p)
end
function convert_arguments(::Type{<: Lines}, rect::Rect3{T}) where {T}
PT = Point3{float_type(T)}
points = unique(decompose(PT, rect))
push!(points, PT(NaN)) # use to seperate linesegments
return (points[[1, 2, 3, 4, 1, 5, 6, 2, 9, 6, 8, 3, 9, 5, 7, 4, 9, 7, 8]],)
end
"""
convert_arguments(PB, LineString)
Takes an input `LineString` and decomposes it to points.
"""
function convert_arguments(PB::PointBased, linestring::LineString)
return convert_arguments(PB, decompose(Point, linestring))
end
"""
convert_arguments(PB, Union{Array{<:LineString}, MultiLineString})
Takes an input `Array{LineString}` or a `MultiLineString` and decomposes it to points.
"""
function convert_arguments(PB::PointBased, linestring::Union{<:AbstractVector{<:LineString{N, T}}, MultiLineString{N, T}}) where {N, T}
T_out = float_type(T)
arr = Point{N, T_out}[]; n = length(linestring)
for idx in 1:n
append!(arr, convert_arguments(PB, linestring[idx])[1])
if idx != n # don't add NaN at the end
push!(arr, Point{N, T_out}(NaN))
end
end
return (arr,)
end
"""
convert_arguments(PB, Polygon)
Takes an input `Polygon` and decomposes it to points.
"""
function convert_arguments(PB::PointBased, pol::Polygon)
converted = convert_arguments(PB, pol.exterior)[1] # this should always be a Tuple{<: Vector{Point}}
arr = copy(converted)
if !isempty(arr) && arr[1] != arr[end]
push!(arr, arr[1]) # close exterior
end
for interior in pol.interiors
push!(arr, Point2(NaN))
inter = convert_arguments(PB, interior)[1] # this should always be a Tuple{<: Vector{Point}}
append!(arr, inter)
if !isempty(inter) && inter[1] != inter[end]
push!(arr, inter[1]) # close interior
end
end
return (arr,)
end
"""
convert_arguments(PB, Union{Array{<:Polygon}, MultiPolygon})
Takes an input `Array{Polygon}` or a `MultiPolygon` and decomposes it to points.
"""
function convert_arguments(PB::PointBased, mp::Union{Array{<:Polygon{N, T}}, MultiPolygon{N, T}}) where {N, T}
arr = Point{N,float_type(T)}[]
n = length(mp)
for idx in 1:n
converted = convert_arguments(PB, mp[idx])[1] # this should always be a Tuple{<: Vector{Point}}
append!(arr, converted)
if idx != n # don't add NaN at the end
push!(arr, Point2(NaN))
end
end
return (arr,)
end
function convert_arguments(::PointBased, b::BezierPath)
b2 = replace_nonfreetype_commands(b)
points = Point2d[]
last_point = Point2d(NaN)
last_moveto = false
function poly3(t, p0, p1, p2, p3)
Point2d((1-t)^3 .* p0 .+ t*p1*(3*(1-t)^2) + p2*(3*(1-t)*t^2) .+ p3*t^3)
end
for command in b2.commands
if command isa MoveTo
last_point = command.p
last_moveto = true
elseif command isa LineTo
if last_moveto
isempty(points) || push!(points, Point2d(NaN, NaN))
push!(points, last_point)
end
push!(points, command.p)
last_point = command.p
last_moveto = false
elseif command isa CurveTo
if last_moveto
isempty(points) || push!(points, Point2d(NaN, NaN))
push!(points, last_point)
end
last_moveto = false
for t in range(0, 1, length = 30)[2:end]
push!(points, poly3(t, last_point, command.c1, command.c2, command.p))
end
last_point = command.p
end
end
return (points,)
end
################################################################################
# GridBased #
################################################################################
function edges(v::AbstractVector{T}) where T
T_out = float_type(T)
l = length(v)
if l == 1
return T_out[v[1] - 0.5, v[1] + 0.5]
else
# Equivalent to
# mids = 0.5 .* (v[1:end-1] .+ v[2:end])
# borders = [2v[1] - mids[1]; mids; 2v[end] - mids[end]]
borders = T_out[0.5 * (v[max(1, i)] + v[min(end, i+1)]) for i in 0:length(v)]
borders[1] = 2borders[1] - borders[2]
borders[end] = 2borders[end] - borders[end-1]
return borders
end
end
function adjust_axes(::CellGrid, x::RealVector, y::RealVector, z::AbstractMatrix)
x̂, ŷ = map((x, y), size(z)) do v, sz
return length(v) == sz ? edges(v) : v
end
return x̂, ŷ, z
end
adjust_axes(::VertexGrid, x, y, z) = x, y, z
"""
convert_arguments(ct::GridBased, x::VecOrMat, y::VecOrMat, z::Matrix)
If `ct` is `Heatmap` and `x` and `y` are vectors, infer from length of `x` and `y`
whether they represent edges or centers of the heatmap bins.
If they are centers, convert to edges. Convert eltypes to `Float32` and return
outputs as a `Tuple`.
"""
function convert_arguments(ct::GridBased, x::AbstractVecOrMat{<:Real}, y::AbstractVecOrMat{<:Real},
z::AbstractMatrix{<:Union{Real,Colorant}})
nx, ny, nz = adjust_axes(ct, x, y, z)
return (float_convert(nx), float_convert(ny), el32convert(nz))
end
convert_arguments(ct::VertexGrid, x::RealMatrix, y::RealMatrix) = convert_arguments(ct, x, y, zeros(size(y)))
"""
convert_arguments(P, x::RangeLike, y::RangeLike, z::AbstractMatrix)
Takes one or two ClosedIntervals `x` and `y` and converts them to closed ranges
with size(z, 1/2).
"""
function convert_arguments(P::GridBased, x::RangeLike, y::RangeLike, z::AbstractMatrix{<: Union{Real, Colorant}})
convert_arguments(P, to_linspace(x, size(z, 1)), to_linspace(y, size(z, 2)), z)
end
function print_range_warning(side::String, value)
@warn "Encountered an `AbstractVector` with value $value on side $side in `convert_arguments` for the `ImageLike` trait.
Using an `AbstractVector` to specify one dimension of an `ImageLike` is deprecated because `ImageLike` sides always need exactly two values, start and stop.
Use interval notation `start .. stop` or a two-element tuple `(start, stop)` instead."
end
to_interval(x::Tuple{<: Real, <: Real}) = float_convert(x[1]) .. float_convert(x[2])
function to_interval(x::Union{Interval,AbstractVector,ClosedInterval})
return float_convert(minimum(x)) .. float_convert(maximum(x))
end
function to_interval(x, dim)
# having minimum and maximum here actually invites bugs
x isa AbstractVector && print_range_warning(dim, x)
return to_interval(x)
end
function convert_arguments(::ImageLike, xs::RangeLike, ys::RangeLike,
data::AbstractMatrix{<:Union{Real,Colorant}})
x = to_interval(xs, "x")
y = to_interval(ys, "y")
return (x, y, el32convert(data))
end
function convert_arguments(ct::GridBased, x::RealVector, y::RealVector, z::RealVector)
if !(length(x) == length(y) == length(z))
error("x, y and z need to have the same length. Lengths are $(length.((x, y, z)))")
end
xys = tuple.(x, y)
if length(unique(xys)) != length(x)
c = StatsBase.countmap(xys)
cdup = filter(x -> x[2] > 1, c)
error("Found duplicate x/y coordinates: $cdup")
end
x_centers = sort(unique(x))
any(isnan, x_centers) && error("x must not have NaN values.")
y_centers = sort(unique(y))
any(isnan, y_centers) && error("x must not have NaN values.")
zs = fill(NaN32, length(x_centers), length(y_centers))
foreach(zip(x, y, z)) do (xi, yi, zi)
i = searchsortedfirst(x_centers, xi)
j = searchsortedfirst(y_centers, yi)
@inbounds zs[i, j] = zi
end
return convert_arguments(ct, x_centers, y_centers, zs)
end
"""
convert_arguments(P, x, y, f)::(Vector, Vector, Matrix)
Takes vectors `x` and `y` and the function `f`, and applies `f` on the grid that `x` and `y` span.
This is equivalent to `f.(x, y')`.
`P` is the plot Type (it is optional).
"""
function convert_arguments(ct::Union{GridBased, ImageLike}, x::AbstractVector, y::AbstractVector, f::Function)
if !applicable(f, x[1], y[1])
error("You need to pass a function with signature f(x::$(eltype(x)), y::$(eltype(y))). Found: $f")
end
return convert_arguments(ct, x, y, f.(x, y'))
end
################################################################################
# VolumeLike #
################################################################################
function convert_arguments(::VolumeLike, x::RangeLike, y::RangeLike, z::RangeLike,
data::RealArray{3})
return (to_interval(x, "x"), to_interval(y, "y"), to_interval(z, "z"), el32convert(data))
end
"""
convert_arguments(P, x, y, z, i)::(Vector, Vector, Vector, Matrix)
Takes 3 `AbstractVector` `x`, `y`, and `z` and the `AbstractMatrix` `i`, and puts everything in a Tuple.
`P` is the plot Type (it is optional).
"""
function convert_arguments(::VolumeLike, x::RealVector, y::RealVector, z::RealVector, i::RealArray{3})
(to_interval(x, "x"), to_interval(y, "y"), to_interval(z, "z"), el32convert(i))
end
################################################################################
# <:Lines #
################################################################################
function convert_arguments(::Type{<: Lines}, x::Rect2{T}) where T
# TODO fix the order of decompose
points = decompose(Point2{float_type(T)}, x)
return (points[[1, 2, 4, 3, 1]],)
end
################################################################################
# <:LineSegments #
################################################################################
"""
Accepts a Vector of Pair of Points (e.g. `[Point(0, 0) => Point(1, 1), ...]`)
to encode e.g. linesegments or directions.
"""
function convert_arguments(::Type{<: LineSegments}, positions::AbstractVector{E}) where E <: Union{Pair{A, A}, Tuple{A, A}} where A <: VecTypes{N, T} where {N, T}
return (float_convert(reinterpret(Point{N,T}, positions)),)
end
function convert_arguments(::Type{<: LineSegments}, x::Rect2{T}) where T
# TODO fix the order of decompose
points = decompose(Point2{float_type(T)}, x)
return (points[[1, 2, 2, 4, 4, 3, 3, 1]],)
end
################################################################################
# <:Mesh #
################################################################################
"""
convert_arguments(Mesh, x, y, z)::GLNormalMesh
Takes real vectors x, y, z and constructs a mesh out of those, under the assumption that
every 3 points form a triangle.
"""
function convert_arguments(
T::Type{<:Mesh},
x::RealVector, y::RealVector, z::RealVector
)
convert_arguments(T, Point3{float_type(x, y, z)}.(x, y, z))
end
"""
convert_arguments(Mesh, xyz::AbstractVector)::GLNormalMesh
Takes an input mesh and a vector `xyz` representing the vertices of the mesh, and
creates indices under the assumption, that each triplet in `xyz` forms a triangle.
"""
function convert_arguments(
MT::Type{<:Mesh},
xyz::AbstractVector
)
faces = connect(UInt32.(0:length(xyz)-1), GLTriangleFace)
# TODO support faceview natively
return convert_arguments(MT, xyz, collect(faces))
end
function convert_arguments(::Type{<:Mesh}, mesh::GeometryBasics.Mesh{N, T}) where {N, T}
T_out = float_type(T)
# Make sure we have normals!
if !hasproperty(mesh, :normals)
n = normals(metafree(decompose(Point, mesh)), faces(mesh))
# Normals can be nothing, when it's impossible to calculate the normals (e.g. 2d mesh)
if !isnothing(n)
mesh = GeometryBasics.pointmeta(mesh; normals=decompose(Vec3f, n))
end
end
# If already correct eltypes for GL, we can pass the mesh through as is
if eltype(metafree(coordinates(mesh))) == Point{N, T_out} && eltype(faces(mesh)) == GLTriangleFace
return (mesh,)
else
# Else, we need to convert it!
return (GeometryBasics.mesh(mesh, pointtype=Point{N, T_out}, facetype=GLTriangleFace),)
end
end
function convert_arguments(
::Type{<:Mesh},
meshes::AbstractVector{<: Union{AbstractMesh, AbstractPolygon}}
)
return (meshes,)
end
function convert_arguments(MT::Type{<:Mesh}, xyz::AbstractPolygon)
m = GeometryBasics.mesh(xyz; pointtype=float_type(xyz), facetype=GLTriangleFace)
return convert_arguments(MT, m)
end
# TODO GeometryBasics can't deal with this directly for Integer Points?
function convert_arguments(
MT::Type{<:Mesh},
xyz::AbstractVector{<: AbstractPoint{2}}
)
ps = float_convert(xyz)
m = GeometryBasics.mesh(ps; pointtype=eltype(ps), facetype=GLTriangleFace)
return convert_arguments(MT, m)
end
function convert_arguments(::Type{<:Mesh}, geom::GeometryPrimitive{N, T}) where {N, T <: Real}
# we convert to UV mesh as default, because otherwise the uv informations get lost
# - we can still drop them, but we can't add them later on
m = GeometryBasics.mesh(geom; pointtype=Point{N,float_type(T)}, uv=Vec2f, normaltype=Vec3f, facetype=GLTriangleFace)
return (m,)
end
"""
convert_arguments(Mesh, x, y, z, indices)::GLNormalMesh
Takes real vectors x, y, z and constructs a triangle mesh out of those, using the
faces in `indices`, which can be integers (every 3 -> one triangle), or GeometryBasics.NgonFace{N, <: Integer}.
"""
function convert_arguments(
T::Type{<: Mesh},
x::RealVector, y::RealVector, z::RealVector,
indices::AbstractVector
)
return convert_arguments(T, Point3{float_type(x, y, z)}.(x, y, z), indices)
end
"""
convert_arguments(Mesh, vertices, indices)::GLNormalMesh
Takes `vertices` and `indices`, and creates a triangle mesh out of those.
See [`to_vertices`](@ref) and [`to_triangles`](@ref) for more information about
accepted types.
"""
function convert_arguments(
::Type{<:Mesh},
vertices::AbstractArray,
indices::AbstractArray
)
vs = to_vertices(vertices)
fs = to_triangles(indices)
if eltype(vs) <: Point{3}
ns = Vec3f.(normals(vs, fs))
m = GeometryBasics.Mesh(meta(vs; normals=ns), fs)
else
# TODO, we don't need to add normals here, but maybe nice for type stability?
m = GeometryBasics.Mesh(meta(vs; normals=fill(Vec3f(0, 0, 1), length(vs))), fs)
end
return (m,)
end
################################################################################
# Function Conversions #
################################################################################
# Allow the user to pass a function to `arrows` which determines the direction
# and magnitude of the arrows. The function must accept `Point2f` as input.
# and return Point2f or Vec2f or some array like structure as output.
function convert_arguments(::Type{<:Arrows}, x::RealVector, y::RealVector, f::Function)
points = Point2{float_type(x, y)}.(x, y')
f_out = Vec2{float_type(x, y)}.(f.(points))
return (vec(points), vec(f_out))
end
function convert_arguments(::Type{<:Arrows}, x::RealVector, y::RealVector, z::RealVector,
f::Function)
points = [Point3{float_type(x, y, z)}(x, y, z) for x in x, y in y, z in z]
f_out = Vec3{float_type(x, y, z)}.(f.(points))
return (vec(points), vec(f_out))
end
"""
convert_arguments(P, x, y, z, f)::(Vector, Vector, Vector, Matrix)
Takes `AbstractVector` `x`, `y`, and `z` and the function `f`, evaluates `f` on the volume
spanned by `x`, `y` and `z`, and puts `x`, `y`, `z` and `f(x,y,z)` in a Tuple.
`P` is the plot Type (it is optional).
"""
function convert_arguments(VL::VolumeLike, x::RealVector, y::RealVector, z::RealVector, f::Function)
if !applicable(f, x[1], y[1], z[1])
error("You need to pass a function with signature f(x, y, z). Found: $f")
end
_x, _y, _z = ntuple(Val(3)) do i
A = (x, y, z)[i]
return reshape(A, ntuple(j -> j != i ? 1 : length(A), Val(3)))
end
# TODO only allow unitranges to map over since we dont support irregular x/y/z values
return (map(to_interval, (x, y, z))..., el32convert.(f.(_x, _y, _z)))
end
function convert_arguments(P::Type{<:AbstractPlot}, r::RealVector, f::Function)
return convert_arguments(P, r, map(f, r))
end
function convert_arguments(P::Type{<:AbstractPlot}, i::AbstractInterval, f::Function)
x, y = PlotUtils.adapted_grid(f, endpoints(i))
return convert_arguments(P, x, y)
end
# OffsetArrays conversions
function convert_arguments(sl::GridBased, wm::OffsetArray)
x1, y1 = wm.offsets .+ 1
nx, ny = size(wm)
x = range(x1, length = nx)
y = range(y1, length = ny)
v = parent(wm)
return convert_arguments(sl, x, y, v)
end
################################################################################
# Helper Functions #
################################################################################
to_linspace(interval, N) = range(minimum(interval), stop = maximum(interval), length = N)
"""
Converts the element array type to `T1` without making a copy if the element type matches
"""
function elconvert(::Type{T1}, x::AbstractArray{T2, N}) where {T1, T2, N}
return convert(AbstractArray{T1, N}, x)
end
function elconvert(::Type{T}, x::AbstractArray{<: Union{Missing, <:Real}}) where {T}
return map(x) do elem
return (ismissing(elem) ? T(NaN) : convert(T, elem))
end
end
float_type(args::Type) = error("Type $(args) not supported")
float_type(a, rest...) = float_type(typeof(a), map(typeof, rest)...)
float_type(a::AbstractArray, rest...) = float_type(float_type(a), map(float_type, rest)...)
float_type(a::AbstractPolygon, rest...) = float_type(float_type(a), map(float_type, rest)...)
float_type(a::Type, rest::Type...) = promote_type(map(float_type, (a, rest...))...)
float_type(::Type{Float64}) = Float64
float_type(::Type{Float32}) = Float32
float_type(::Type{<:Real}) = Float64
float_type(::Type{<:Union{Int8,UInt8,Int16,UInt16}}) = Float32
float_type(::Type{<:Union{Float16}}) = Float32
float_type(::Type{Point{N,T}}) where {N,T} = Point{N,float_type(T)}
float_type(::Type{Vec{N,T}}) where {N,T} = Vec{N,float_type(T)}
float_type(::Type{NTuple{N, T}}) where {N,T} = Point{N,float_type(T)}
float_type(::Type{Tuple{T1, T2}}) where {T1,T2} = Point2{promote_type(float_type(T1), float_type(T2))}
float_type(::Type{Tuple{T1, T2, T3}}) where {T1,T2,T3} = Point3{promote_type(float_type(T1), float_type(T2), float_type(T3))}
float_type(::Type{Union{Missing, T}}) where {T} = float_type(T)
float_type(::Type{Union{Nothing,T}}) where {T} = float_type(T)
float_type(::Type{ClosedInterval{T}}) where {T} = ClosedInterval{T}
float_type(::Type{ClosedInterval}) = ClosedInterval{Float32}
float_type(::AbstractArray{T}) where {T} = float_type(T)
float_type(::AbstractPolygon{N, T}) where {N, T} = Point{N, float_type(T)}
float_convert(x) = convert(float_type(x), x)
float_convert(x::AbstractArray{Float32}) = x
float_convert(x::AbstractArray{Float64}) = x
float_convert(x::AbstractArray) = elconvert(float_type(x), x)
float_convert(x::Observable) = lift(float_convert, x)
float_convert(x::AbstractArray{<:Union{Missing, T}}) where {T<:Real} = elconvert(float_type(T), x)
float32type(::Type{<:Real}) = Float32
float32type(::Type{Point{N,T}}) where {N,T} = Point{N,float32type(T)}
float32type(::Type{Vec{N,T}}) where {N,T} = Vec{N,float32type(T)}
# We may want to always use UInt8 for colors?
float32type(::Type{<: RGB}) = RGB{Float32}
float32type(::Type{<: RGBA}) = RGBA{Float32}
float32type(::Type{<: Colorant}) = RGBA{Float32}
float32type(::AbstractArray{T}) where T = float32type(T)
float32type(::T) where {T} = float32type(T)
el32convert(x::ClosedInterval) = Float32(minimum(x)) .. Float32(maximum(x))
el32convert(x::AbstractArray) = elconvert(float32type(x), x)
el32convert(x::AbstractArray{T}) where {T<:Real} = elconvert(float32type(T), x)
el32convert(x::AbstractArray{<:Union{Missing,T}}) where {T<:Real} = elconvert(float32type(T), x)
el32convert(x::AbstractArray{Float32}) = x
el32convert(x::Observable) = lift(el32convert, x)
el32convert(x) = convert(float32type(x), x)
el32convert(x::Mat{X, Y, T}) where {X, Y, T} = Mat{X, Y, Float32}(x)
"""
to_triangles(indices)
Convert a representation of triangle point indices `indices` to its canonical representation as a `Vector{Makie.GLTriangleFace}`. `indices` can be any of the following:
- An `AbstractVector{Int}`, containing groups of 3 1-based indices,
- An `AbstractVector{UIn32}`, containing groups of 3 0-based indices,
- An `AbstractVector` of `TriangleFace` objects,
- An `AbstractMatrix` of `Integer`s, where each row is a triangle.
"""
function to_triangles(x::AbstractVector{Int})
idx0 = UInt32.(x .- 1)
return to_triangles(idx0)
end
function to_triangles(idx0::AbstractVector{UInt32})
reinterpret(GLTriangleFace, idx0)
end
function to_triangles(faces::AbstractVector{TriangleFace{T}}) where T
elconvert(GLTriangleFace, faces)
end
function to_triangles(faces::AbstractMatrix{T}) where T <: Integer
@assert size(faces, 2) == 3
return broadcast(1:size(faces, 1), 3) do fidx, n
GLTriangleFace(ntuple(i-> faces[fidx, i], n))
end
end
"""
to_vertices(v)
Converts a representation of vertices `v` to its canonical representation as a
`Vector{Point3f}`. `v` can be:
- An `AbstractVector` of 3-element `Tuple`s or `StaticVector`s,
- An `AbstractVector` of `Tuple`s or `StaticVector`s, in which case extra dimensions will
be either truncated or padded with zeros as required,
- An `AbstractMatrix`"
- if `v` has 2 or 3 rows, it will treat each column as a vertex,
- otherwise if `v` has 2 or 3 columns, it will treat each row as a vertex.
"""
function to_vertices(verts::AbstractVector{<: VecTypes{3, T}}) where T
T_out = float_type(T)
vert3 = T != T_out ? map(Point3{T_out}, verts) : verts
return reinterpret(Point3{T_out}, vert3)
end
function to_vertices(verts::AbstractVector{<: VecTypes{N, T}}) where {N, T}
return map(Point{N, float_type(T)}, verts)
end
function to_vertices(verts::AbstractMatrix{<: Real})
if size(verts, 1) in (2, 3)
to_vertices(verts, Val(1))
elseif size(verts, 2) in (2, 3)
to_vertices(verts, Val(2))
else
error("You are using a matrix for vertices which uses neither dimension to encode the dimension of the space. Please have either size(verts, 1/2) in the range of 2-3. Found: $(size(verts))")
end
end
function to_vertices(verts::AbstractMatrix{T}, ::Val{1}) where T <: Real
N = size(verts, 1)
if T == float_type(T) && N == 3
reinterpret(Point{N, T}, elconvert(T, vec(verts)))
else
let N = Val(N); lverts = verts; T_out = float_type(T)
broadcast(1:size(verts, 2), N) do vidx, n
Point(ntuple(i-> T_out(lverts[i, vidx]), n))
end
end
end
end
function to_vertices(verts::AbstractMatrix{T}, ::Val{2}) where T <: Real
let N = Val(size(verts, 2)); lverts = verts; T_out = float_type(T)
broadcast(1:size(verts, 1), N) do vidx, n
Point(ntuple(i-> T_out(lverts[vidx, i]), n))
end
end
end
################################################################################
### Unused?
################################################################################
# The following `tryrange` code was copied from Plots.jl
# https://github.com/MakieOrg/Plots.jl/blob/15dc61feb57cba1df524ce5d69f68c2c4ea5b942/src/series.jl#L399-L416
# try some intervals over which the function may be defined
function tryrange(F::AbstractArray, vec)
rets = [tryrange(f, vec) for f in F] # get the preferred for each
maxind = maximum(indexin(rets, vec)) # get the last attempt that succeeded (most likely to fit all)
rets .= [tryrange(f, vec[maxind:maxind]) for f in F] # ensure that all functions compute there
rets[1]
end
function tryrange(F, vec)
for v in vec
try
tmp = F(v)
return v
catch
end
end
error("$F is not a Function, or is not defined at any of the values $vec")
end
################################################################################
# Attribute conversions #
################################################################################
convert_attribute(x, key::Key, ::Key) = convert_attribute(x, key)
convert_attribute(s::SceneLike, x, key::Key, ::Key) = convert_attribute(s, x, key)
convert_attribute(s::SceneLike, x, key::Key) = convert_attribute(x, key)
convert_attribute(x, key::Key) = x
convert_attribute(color, ::key"color") = to_color(color)
convert_attribute(colormap, ::key"colormap") = to_colormap(colormap)
convert_attribute(font, ::key"font") = to_font(font)
convert_attribute(align, ::key"align") = to_align(align)
convert_attribute(p, ::key"highclip") = to_color(p)
convert_attribute(p::Nothing, ::key"highclip") = p
convert_attribute(p, ::key"lowclip") = to_color(p)
convert_attribute(p::Nothing, ::key"lowclip") = p
convert_attribute(p, ::key"nan_color") = to_color(p)
struct Palette
colors::Vector{RGBA{Float32}}
i::Ref{Int}
Palette(colors) = new(to_color.(colors), zero(Int))
end
Palette(name::Union{String, Symbol}, n = 8) = Palette(categorical_colors(name, n))
function to_color(p::Palette)
N = length(p.colors)
p.i[] = p.i[] == N ? 1 : p.i[] + 1
return p.colors[p.i[]]
end
to_color(c::Nothing) = c # for when color is not used
to_color(c::Real) = Float32(c)
to_color(c::Colorant) = convert(RGBA{Float32}, c)
to_color(c::Symbol) = to_color(string(c))
to_color(c::String) = parse(RGBA{Float32}, c)
to_color(c::AbstractArray) = to_color.(c)
to_color(c::AbstractArray{<: Colorant, N}) where N = convert(Array{RGBAf, N}, c)
to_color(p::AbstractPattern) = p
function to_color(c::Tuple{<: Any, <: Number})
col = to_color(c[1])
return RGBAf(Colors.color(col), alpha(col) * c[2])
end
convert_attribute(b::Billboard{Float32}, ::key"rotation") = to_rotation(b.rotation)
convert_attribute(b::Billboard{Vector{Float32}}, ::key"rotation") = to_rotation.(b.rotation)
convert_attribute(r::AbstractArray, ::key"rotation") = to_rotation.(r)
convert_attribute(r::StaticVector, ::key"rotation") = to_rotation(r)
convert_attribute(r, ::key"rotation") = to_rotation(r)
convert_attribute(c, ::key"markersize", ::key"scatter") = to_2d_scale(c)
convert_attribute(c, ::key"markersize", ::key"meshscatter") = to_3d_scale(c)
to_2d_scale(x::Number) = Vec2f(x)
to_2d_scale(x::VecTypes) = to_ndim(Vec2f, x, 1)
to_2d_scale(x::Tuple{<:Number, <:Number}) = to_ndim(Vec2f, x, 1)
to_2d_scale(x::AbstractVector) = to_2d_scale.(x)
to_3d_scale(x::Number) = Vec3f(x)
to_3d_scale(x::VecTypes) = to_ndim(Vec3f, x, 1)
to_3d_scale(x::AbstractVector) = to_3d_scale.(x)
convert_attribute(x, ::key"uv_offset_width") = Vec4f(x)
convert_attribute(x::AbstractVector{Vec4f}, ::key"uv_offset_width") = x
convert_attribute(c::Number, ::key"glowwidth") = Float32(c)
convert_attribute(c::Number, ::key"strokewidth") = Float32(c)
convert_attribute(c, ::key"glowcolor") = to_color(c)
convert_attribute(c, ::key"strokecolor") = to_color(c)
####
## Line style conversions
####
convert_attribute(style, ::key"linestyle") = to_linestyle(style)
to_linestyle(::Nothing) = nothing
# add deprecation for old conversion
function convert_attribute(style::AbstractVector, ::key"linestyle")
@warn "Using a `Vector{<:Real}` as a linestyle attribute is deprecated. Wrap it in a `Linestyle`."
return to_linestyle(Linestyle(style))
end
"""
Linestyle(value::Vector{<:Real})
A type that can be used as value for the `linestyle` keyword argument
of plotting functions to arbitrarily customize the linestyle.
The `value` is a vector of positions where the line flips from being drawn or not
and vice versa. The values of `value` are in units of linewidth.
For example, with `value = [0.0, 4.0, 6.0, 9.5]`
you start drawing at 0, stop at 4 linewidths, start again at 6, stop at 9.5,
then repeat with 0 and 9.5 being treated as the same position.
"""
struct Linestyle
value::Vector{Float32}
end
to_linestyle(style::Linestyle) = Float32[x - style.value[1] for x in style.value]
# TODO only use NTuple{2, <: Real} and not any other container
const GapType = Union{Real, Symbol, Tuple, AbstractVector}
# A `Symbol` equal to `:dash`, `:dot`, `:dashdot`, `:dashdotdot`
to_linestyle(ls::Union{Symbol, AbstractString}) = line_pattern(ls, :normal)
function to_linestyle(ls::Tuple{<:Union{Symbol, AbstractString}, <: GapType})
return line_pattern(ls[1], ls[2])
end
function line_pattern(linestyle::Symbol, gaps::GapType)
pattern = line_diff_pattern(linestyle, gaps)
return isnothing(pattern) ? pattern : Float32[0.0; cumsum(pattern)]
end
"The linestyle patterns are inspired by the LaTeX package tikZ as seen here https://tex.stackexchange.com/questions/45275/tikz-get-values-for-predefined-dash-patterns."
function line_diff_pattern(ls::Symbol, gaps::GapType = :normal)
if ls === :solid
return nothing
elseif ls === :dash
return line_diff_pattern("-", gaps)
elseif ls === :dot
return line_diff_pattern(".", gaps)
elseif ls === :dashdot
return line_diff_pattern("-.", gaps)
elseif ls === :dashdotdot
return line_diff_pattern("-..", gaps)
else
error(
"""
Unkown line style: $ls. Available linestyles are:
:solid, :dash, :dot, :dashdot, :dashdotdot
or a sequence of numbers enumerating the next transparent/opaque region.
This sequence of numbers must be cumulative; 1 unit corresponds to 1 line width.
"""
)
end
end
function line_diff_pattern(ls_str::AbstractString, gaps::GapType = :normal)
dot = 1
dash = 3
check_line_pattern(ls_str)
dot_gap, dash_gap = convert_gaps(gaps)
pattern = Float64[]
for i in 1:length(ls_str)
curr_char = ls_str[i]
next_char = i == lastindex(ls_str) ? ls_str[firstindex(ls_str)] : ls_str[i+1]
# push dash or dot
if curr_char == '-'
push!(pattern, dash)
else
push!(pattern, dot)
end