-
Notifications
You must be signed in to change notification settings - Fork 233
/
geom.py
2586 lines (2200 loc) · 82.3 KB
/
geom.py
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
# ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ##### END GPL LICENSE BLOCK #####
'''
Eventual purpose of this file is to store the convenience functions which
can be used for regular nodes or as part of recipes for script nodes. These
functions will initially be sub optimal quick implementations,
then optimized only for speed, never for aesthetics or line count or cleverness.
'''
import math
from math import sin, cos, sqrt, acos, pi, atan
import numpy as np
from numpy import linalg
from functools import wraps
import time
import bpy
import bmesh
import mathutils
from mathutils import Matrix, Vector
from mathutils.geometry import interpolate_bezier, intersect_line_line, intersect_point_line
from sverchok.utils.modules.geom_primitives import (
circle, arc, quad, arc_slice, rect, grid, line)
from sverchok.utils.sv_bmesh_utils import bmesh_from_pydata
from sverchok.utils.sv_bmesh_utils import pydata_from_bmesh
from sverchok.data_structure import match_long_repeat, describe_data_shape
from sverchok.utils.math import np_mixed_product
from sverchok.utils.logging import debug, info
identity_matrix = Matrix()
# constants
PI = math.pi
HALF_PI = PI / 2
QUARTER_PI = PI / 4
TAU = PI * 2
TWO_PI = TAU
N = identity_matrix
# ----------------- vectorize wrapper ---------------
def vectorize(func):
'''
Will create a yielding vectorized generator of the
function it is applied to.
Note: parameters must be passed as kw arguments
'''
@wraps(func)
def inner(**kwargs):
names, values = kwargs.keys(), kwargs.values()
values = match_long_repeat(values)
multiplex = {k:v for k, v in zip(names, values)}
for i in range(len(values[0])):
single_kwargs = {k:v[i] for k, v in multiplex.items()}
yield func(**single_kwargs)
return inner
# ----------------- sn1 specific helper for autowrapping to iterables ----
# this will be moved to elsewhere.
def sn1_autowrap(*params):
for p in params:
if isinstance(p, (float, int)):
p = [p]
yield p
def sn1_autodict(names, var_dict):
return {k:v for k, v in var_dict.items() if k in set(names.split(' '))}
# ----------- vectorized forms
arcs = vectorize(arc)
arc_slices = vectorize(arc_slice)
circles = vectorize(circle)
quads = vectorize(quad)
rects = vectorize(rect)
lines = vectorize(line)
grids = vectorize(grid)
################################################
# Newer implementation of spline interpolation
# by zeffii, ly29 and portnov
# based on implementation from looptools 4.5.2 done by Bart Crouch
# factored out from interpolation_mk3 node
################################################
class Spline(object):
"""
Base abstract class for LinearSpline and CubicSpline.
"""
@classmethod
def create_knots(cls, pts, metric="DISTANCE"):
#if not isinstance(pts, np.ndarray):
# raise TypeError(f"Unexpected data: {pts}")
if metric == "DISTANCE":
tmp = np.linalg.norm(pts[:-1] - pts[1:], axis=1)
tknots = np.insert(tmp, 0, 0).cumsum()
if tknots[-1] != 0:
tknots = tknots / tknots[-1]
elif metric == "MANHATTAN":
tmp = np.sum(np.absolute(pts[:-1] - pts[1:]), 1)
tknots = np.insert(tmp, 0, 0).cumsum()
if tknots[-1] != 0:
tknots = tknots / tknots[-1]
elif metric == "POINTS":
tknots = np.linspace(0, 1, len(pts))
elif metric == "CHEBYSHEV":
tknots = np.max(np.absolute(pts[1:] - pts[:-1]), 1)
tknots = np.insert(tknots, 0, 0).cumsum()
if tknots[-1] != 0:
tknots = tknots / tknots[-1]
elif metric == 'CENTRIPETAL':
tmp = np.linalg.norm(pts[:-1] - pts[1:], axis=1)
tmp = np.sqrt(tmp)
tknots = np.insert(tmp, 0, 0).cumsum()
if tknots[-1] != 0:
tknots = tknots / tknots[-1]
elif metric == "X":
tknots = pts[:,0]
tknots = tknots - tknots[0]
if tknots[-1] != 0:
tknots = tknots / tknots[-1]
elif metric == "Y":
tknots = pts[:,1]
tknots = tknots - tknots[0]
if tknots[-1] != 0:
tknots = tknots / tknots[-1]
elif metric == "Z":
tknots = pts[:,2]
tknots = tknots - tknots[0]
if tknots[-1] != 0:
tknots = tknots / tknots[-1]
return tknots
def __init__(self):
# Caches
# t -> vertex
self._single_eval_cache = {}
def length(self, t_in):
"""
t_in: np.array with values in [0,1]
"""
t_in = t_in.copy()
t_in.sort()
points_on_spline = self.eval(t_in)
t = points_on_spline[:-1] - points_on_spline[1:]
norms = np.linalg.norm(t, axis=1)
return norms.sum()
def eval_at_point(self, t):
"""
Evaluate spline at single point.
t: float in [0,1].
Returns vector in Sverchok format (tuple of floats).
"""
result = self._single_eval_cache.get(t, None)
if result is not None:
return result
else:
result = self.eval(np.array([t]))
result = tuple(result[0])
self._single_eval_cache[t] = result
return result
class CubicSpline(Spline):
def __init__(self, vertices, tknots = None, metric = None, is_cyclic = False):
"""
vertices: vertices in Sverchok's format (list of tuples)
tknots: np.array of shape (n-1,). If not provided - calculated automatically based on metric
metric: string, one of "DISTANCE", "MANHATTAN", "POINTS", "CHEBYSHEV". Mandatory if tknots
is not provided
is_cyclic: whether the spline is cyclic
creates a cubic spline through the locations given in vertices
"""
super().__init__()
if is_cyclic:
#print(describe_data_shape(vertices))
locs = np.array(vertices[-4:] + vertices + vertices[:4])
if tknots is None:
if metric is None:
raise Exception("CubicSpline: either tknots or metric must be specified")
tknots = Spline.create_knots(locs, metric)
scale = 1 / (tknots[-4] - tknots[4])
base = tknots[4]
tknots -= base
tknots *= scale
else:
locs = np.array(vertices)
if tknots is None:
if metric is None:
raise Exception("CubicSpline: either tknots or metric must be specified")
tknots = Spline.create_knots(locs, metric)
self.tknots = tknots
self.is_cyclic = is_cyclic
self.pts = np.array(vertices)
n = len(locs)
if n < 2:
raise Exception("Cubic spline can't be build from less than 3 vertices")
# a = locs
h = tknots[1:] - tknots[:-1]
h[h == 0] = 1e-8
q = np.zeros((n - 1, 3))
q[1:] = 3 / h[1:, np.newaxis] * (locs[2:] - locs[1:-1]) - 3 / \
h[:-1, np.newaxis] * (locs[1:-1] - locs[:-2])
l = np.zeros((n, 3))
l[0, :] = 1.0
u = np.zeros((n - 1, 3))
z = np.zeros((n, 3))
for i in range(1, n - 1):
l[i] = 2 * (tknots[i + 1] - tknots[i - 1]) - h[i - 1] * u[i - 1]
l[i, l[i] == 0] = 1e-8
u[i] = h[i] / l[i]
z[i] = (q[i] - h[i - 1] * z[i - 1]) / l[i]
l[-1, :] = 1.0
z[-1] = 0.0
b = np.zeros((n - 1, 3))
c = np.zeros((n, 3))
for i in range(n - 2, -1, -1):
c[i] = z[i] - u[i] * c[i + 1]
b = (locs[1:] - locs[:-1]) / h[:, np.newaxis] - h[:, np.newaxis] * (c[1:] + 2 * c[:-1]) / 3
d = (c[1:] - c[:-1]) / (3 * h[:, np.newaxis])
splines = np.zeros((n - 1, 5, 3))
splines[:, 0] = locs[:-1]
splines[:, 1] = b
splines[:, 2] = c[:-1]
splines[:, 3] = d
splines[:, 4] = tknots[:-1, np.newaxis]
self.splines = splines
def eval(self, t_in, tknots = None):
"""
Evaluate the spline at the points in t_in, which must be an array
with values in [0,1]
returns and np array with the corresponding points
"""
if tknots is None:
tknots = self.tknots
index = tknots.searchsorted(t_in, side='left') - 1
index = index.clip(0, len(self.splines) - 1)
to_calc = self.splines[index]
ax, bx, cx, dx, tx = np.swapaxes(to_calc, 0, 1)
t_r = t_in[:, np.newaxis] - tx
out = ax + t_r * (bx + t_r * (cx + t_r * dx))
return out
def get_degree(self):
return 3
def get_t_segments(self):
N = len(self.pts)
if self.is_cyclic:
index = np.array(range(4, 4+N+1))
else:
index = np.array(range(N-1))
return list(zip(self.tknots[index], self.tknots[index+1]))
def get_control_points(self, index=None):
"""
Returns: np.array of shape (M, 4, 3),
where M is the number of Bezier segments, i.e.
M = N - 1, where N is the number of points being interpolated.
"""
if index is None:
N = len(self.pts)
if self.is_cyclic:
index = np.array(range(4, 4+N))
else:
index = np.array(range(N-1))
#n = len(index)
to_calc = self.splines[index]
a, b, c, d, tx = np.swapaxes(to_calc, 0, 1)
tknots = np.append(self.tknots, 1.0)
T = (tknots[index+1] - tknots[index])[np.newaxis].T
p0 = a
p1 = (T*b+3*a)/3.0
p2 = (T**2*c+2*T*b+3*a)/3.0
p3 = T**3*d+T**2*c+T*b+a
return np.transpose(np.array([p0, p1, p2, p3]), axes=(1,0,2))
# def integrate(self, t_in, tknots=None):
# if tknots is None:
# tknots = self.tknots
#
# index = tknots.searchsorted(t_in, side='left') - 1
# index = index.clip(0, len(self.splines) - 1)
# to_calc = self.splines[index]
# ax, bx, cx, dx, tx = np.swapaxes(to_calc, 0, 1)
# bx /= 2.0
# cx /= 3.0
# dx /= 4.0
# t_r = t_in[:, np.newaxis] - tx
# out = ax + t_r * (bx + t_r * (cx + t_r * dx))
# out = t_r * out
# return out
def tangent(self, t_in, h=0.001, tknots=None):
"""
Calc numerical tangents for spline at t_in
"""
if tknots is None:
tknots = self.tknots
t_ph = t_in + h
t_mh = t_in - h
t_less_than_0 = t_mh < 0.0
t_great_than_1 = t_ph > 1.0
t_mh[t_less_than_0] += h
t_ph[t_great_than_1] -= h
tanget_ph = self.eval(t_ph)
tanget_mh = self.eval(t_mh)
tanget = tanget_ph - tanget_mh
tanget[t_less_than_0 | t_great_than_1] *= 2
return tanget / h
class LinearSpline(Spline):
def __init__(self, vertices, tknots = None, metric = None, is_cyclic = False):
"""
vertices: vertices in Sverchok's format (list of tuples)
tknots: np.array of shape (n-1,). If not provided - calculated automatically based on metric
metric: string, one of "DISTANCE", "MANHATTAN", "POINTS", "CHEBYSHEV". Mandatory if tknots
is not provided
is_cyclic: whether the spline is cyclic
creates a cubic spline through the locations given in vertices
"""
super().__init__()
if is_cyclic:
pts = np.array(vertices + [vertices[0]])
else:
pts = np.array(vertices)
if tknots is None:
if metric is None:
raise Exception("LinearSpline: either tknots or metric must be specified")
tknots = Spline.create_knots(pts, metric)
self.pts = pts
self.tknots = tknots
self.is_cyclic = is_cyclic
def get_t_segments(self):
return list(zip(self.tknots, self.tknots[1:]))
def get_degree(self):
return 1
def get_control_points(self):
starts = self.pts[:-1]
ends = self.pts[1:]
return np.transpose(np.stack((starts, ends)), axes=(1,0,2))
def eval(self, t_in, tknots = None):
"""
Eval the liner spline f(t) = x,y,z through the points
in pts given the knots in tknots at the point in t_in
"""
if tknots is None:
tknots = self.tknots
ptsT = self.pts.T
out = np.zeros((3, len(t_in)))
for i in range(3):
out[i] = np.interp(t_in, tknots, ptsT[i])
return out.T
def tangent(self, t_in, tknots = None, h = None):
if tknots is None:
tknots = self.tknots
lookup_segments = GenerateLookup(self.is_cyclic, self.pts.tolist())
return np.array([lookup_segments.find_bucket(f) for f in t_in])
class Spline2D(object):
"""
2D Spline (surface).
Composed by putting 1D splines along V direction, and then interpolating
across them (in U direction) by using another series of 1D splines.
U and V splines can both be either linear or cubic.
The spline can optionally be cyclic in U and/or V directions
(so it can form a cylindrical or thoroidal surface).
This is implemented partly in pure python, partly in numpy, so the performance
is not very good. The performance is not very bad either, because of caching.
"""
def __init__(self, vertices,
u_spline_constructor = CubicSpline, v_spline_constructor = None,
metric = "DISTANCE",
is_cyclic_u = False, is_cyclic_v = False):
"""
vertices: Vertices in Sverchok format, i.e. list of list of 3-tuples.
u_spline_constructor: constructor of Spline objects.
v_spline_constructor: constructor of Spline objects. Defaults to u_spline_constructor.
is_cyclic_u: whether the spline is cyclic in the U direction
is_cyclic_v: whether the spline is cyclic in the V direction
metric: string, one of "DISTANCE", "MANHATTAN", "POINTS", "CHEBYSHEV".
"""
self.vertices = np.array(vertices)
if v_spline_constructor is None:
v_spline_constructor = u_spline_constructor
self.u_spline_constructor = u_spline_constructor
self.v_spline_constructor = v_spline_constructor
self.metric = metric
self.is_cyclic_u = is_cyclic_u
self.is_cyclic_v = is_cyclic_v
self._v_splines = [v_spline_constructor(verts, is_cyclic=is_cyclic_v, metric=metric) for verts in vertices]
# Caches
# v -> Spline
self._u_splines = {}
# (u,v) -> vertex
self._eval_cache = {}
# (u,v) -> normal
self._normal_cache = {}
def get_u_spline(self, v, vertices):
"""Get a spline along U direction for specified value of V coordinate"""
spline = self._u_splines.get(v, None)
if spline is not None:
return spline
else:
spline = self.u_spline_constructor(vertices, is_cyclic=self.is_cyclic_u, metric=self.metric)
self._u_splines[v] = spline
return spline
def eval(self, u, v):
"""
u, v: floats in [0, 1].
Returns 3-tuple of floats.
Evaluate the spline at single point.
"""
result = self._eval_cache.get((u,v), None)
if result is not None:
return result
else:
spline_vertices = [spline.eval_at_point(v) for spline in self._v_splines]
u_spline = self.get_u_spline(v, spline_vertices)
result = u_spline.eval_at_point(u)
self._eval_cache[(u,v)] = result
return result
def normal(self, u, v, h=0.001):
"""
u, v: floats in [0,1].
h: step for numeric differentials calculation.
Returns 3-tuple of floats.
Get the normal vector for spline at specific point.
"""
result = self._normal_cache.get((u,v), None)
if result is not None:
return result
else:
point = np.array(self.eval(u, v))
point_u = np.array(self.eval(u+h, v))
point_v = np.array(self.eval(u, v+h))
du = (point_u - point)/h
dv = (point_v - point)/h
n = np.cross(du, dv)
norm = np.linalg.norm(n)
if norm != 0:
n = n / norm
#debug("DU: {}, DV: {}, N: {}".format(du, dv, n))
result = tuple(n)
self._normal_cache[(u,v)] = result
return result
class GenerateLookup():
def __init__(self, cyclic, vlist):
self.lookup = {}
self.summed_lengths = []
self.indiv_lengths = []
self.normals = []
self.buckets = []
if cyclic:
vlist = vlist + [vlist[0]]
self.get_seq_len(vlist)
self.acquire_lookup_table()
self.get_buckets()
# for idx, (k, v) in enumerate(sorted(self.lookup.items())):
# debug(k, v)
def find_bucket(self, factor):
for bucket_min, bucket_max in zip(self.buckets[:-1], self.buckets[1:]):
if bucket_min <= factor < bucket_max:
tval = self.lookup.get(bucket_min) # , self.lookup.get(self.buckets[-1]))
return tval
# return last bucket just in case
return self.lookup.get(self.buckets[-1])
def get_buckets(self):
self.buckets = [(clen / self.total_length) for clen in self.summed_lengths]
def acquire_lookup_table(self):
for current_length, segment_normal in zip(self.summed_lengths, self.normals):
self.lookup[current_length / self.total_length] = segment_normal
def get_seq_len(self, vlist):
add_len = self.indiv_lengths.append
add_normal = self.normals.append
add_to_sumlist = self.summed_lengths.append
current_length = 0.0
for idx in range(len(vlist)-1):
v = vlist[idx][0]-vlist[idx+1][0], vlist[idx][1]-vlist[idx+1][1], vlist[idx][2]-vlist[idx+1][2]
length = math.sqrt((v[0]*v[0]) + (v[1]*v[1]) + (v[2]*v[2]))
add_normal(v)
add_len(length)
add_to_sumlist(current_length)
current_length += length
self.total_length = sum(self.indiv_lengths)
def householder(u):
'''
Calculate Householder reflection matrix.
u: mathutils.Vector or tuple of 3 floats.
returns mathutils.Matrix.
'''
x,y,z = u[0], u[1], u[2]
m = Matrix([[x*x, x*y, x*z, 0], [x*y, y*y, y*z, 0], [x*z, y*z, z*z, 0], [0,0,0,0]])
h = Matrix() - 2*m
return h
def autorotate_householder(e1, xx):
'''
A matrix of transformation which will transform xx vector into e1,
calculated via Householder matrix.
See http://en.wikipedia.org/wiki/QR_decomposition
e1, xx: mathutils.Vector.
returns mathutils.Matrix.
'''
sign = -1
alpha = xx.length * sign
u = xx - alpha*e1
v = u.normalized()
q = householder(v)
return q
def autorotate_track(e1, xx, up):
'''
A matrix of transformation which will transform xx vector into e1,
calculated via Blender's to_track_quat method.
e1: string, one of "X", "Y", "Z"
xx: mathutils.Vector.
up: string, one of "X", "Y", "Z".
returns mathutils.Matrix.
'''
rotation = xx.to_track_quat(e1, up)
return rotation.to_matrix().to_4x4()
def autorotate_diff(e1, xx):
'''
A matrix of transformation which will transform xx vector into e1,
calculated via Blender's rotation_difference method.
e1, xx: mathutils.Vector.
returns mathutils.Matrix.
'''
return xx.rotation_difference(e1).to_matrix().to_4x4()
def diameter(vertices, axis):
"""
Calculate diameter of set of vertices along specified axis.
vertices: list of mathutils.Vector or of 3-tuples of floats.
axis: either
* integer: 0, 1 or 2 for X, Y or Z
* string: 'X', 'Y' or 'Z'
* 3-tuple of floats or Vector: any direction
* None: calculate diameter regardless of direction
returns float.
"""
if axis is None:
distances = [(mathutils.Vector(v1) - mathutils.Vector(v2)).length for v1 in vertices for v2 in vertices]
return max(distances)
elif isinstance(axis, tuple) or isinstance(axis, Vector):
axis = mathutils.Vector(axis).normalized()
ds = [mathutils.Vector(vertex).dot(axis) for vertex in vertices]
M = max(ds)
m = min(ds)
return (M-m)
else:
if axis == 'X':
axis = 0
elif axis == 'Y':
axis = 1
elif axis == 'Z':
axis = 2
elif isinstance(axis, str):
raise Exception("Unknown axis: {}".format(axis))
xs = [vertex[axis] for vertex in vertices]
M = max(xs)
m = min(xs)
return (M-m)
def center(data):
"""
input: data - a list of 3-tuples or numpy array of same shape
output: 3-tuple - arithmetical average of input vertices (barycenter)
"""
array = np.array(data)
n = array.shape[0]
center = array.sum(axis=0) / n
return tuple(center)
def interpolate_quadratic_bezier(knot1, handle, knot2, resolution):
"""
Interpolate a quadartic bezier spline segment.
Quadratic bezier curve is defined by two knots (at the beginning and at the
end of segment) and one handle.
Quadratic bezier curves is a special case of cubic bezier curves, which
are implemented in blender. So this function just converts input data
and calls for interpolate_bezier.
"""
if not isinstance(knot1, mathutils.Vector):
knot1 = mathutils.Vector(knot1)
if not isinstance(knot2, mathutils.Vector):
knot2 = mathutils.Vector(knot2)
if not isinstance(handle, mathutils.Vector):
handle = mathutils.Vector(handle)
handle1 = knot1 + (2.0/3.0) * (handle - knot1)
handle2 = handle + (1.0/3.0) * (knot2 - handle)
return interpolate_bezier(knot1, handle1, handle2, knot2, resolution)
def calc_normal(vertices):
"""
Calculate normal for a face defined by specified vertices.
For tris or quads, mathutils.geometry.normal() is used.
Ngon will be triangulated, and then the average normal of
all resulting tris will be returned.
input: list of 3-tuples or list of mathutils.Vector.
output: mathutils.Vector.
"""
n = len(vertices)
vertices = list(map(mathutils.Vector, vertices))
if n <= 4:
return mathutils.geometry.normal(*vertices)
else:
# Triangluate
triangle_idxs = [[0, k, k+1] for k in range(1, n-1)]
triangles = [[vertices[i] for i in idxs] for idxs in triangle_idxs]
subnormals = [mathutils.geometry.normal(*triangle) for triangle in triangles]
return mathutils.Vector(center(subnormals))
class PlaneEquation(object):
"""
An object, containing the coefficients A, B, C, D in the equation of a
plane:
A*x + B*y + C*z + D = 0
"""
def __init__(self, a, b, c, d):
self.a = a
self.b = b
self.c = c
self.d = d
def __repr__(self):
return "[{}, {}, {}, {}]".format(self.a, self.b, self.c, self.d)
def __str__(self):
return "{}x + {}y + {}z + {} = 0".format(self.a, self.b, self.c, self.d)
@classmethod
def from_normal_and_point(cls, normal, point):
a, b, c = tuple(normal)
if (a*a + b*b + c*c) < 1e-8:
raise Exception("Plane normal is (almost) zero!")
cx, cy, cz = tuple(point)
d = - (a*cx + b*cy + c*cz)
return PlaneEquation(a, b, c, d)
@classmethod
def from_three_points(cls, p1, p2, p3):
x1, y1, z1 = p1[0], p1[1], p1[2]
x2, y2, z2 = p2[0], p2[1], p2[2]
x3, y3, z3 = p3[0], p3[1], p3[2]
a = (y2 - y1)*(z3-z1) - (z2 - z1)*(y3 - y1)
b = - (x2 - x1)*(z3-z1) + (z2 - z1)*(x3 - x1)
c = (x2 - x1)*(y3 - y1) - (y2 - y1)*(x3 - x1)
return PlaneEquation.from_normal_and_point((a, b, c), p1)
@classmethod
def from_point_and_two_vectors(cls, point, v1, v2):
normal = v1.cross(v2)
return PlaneEquation.from_normal_and_point(normal, point)
@classmethod
def from_coordinate_plane(cls, plane_name):
if plane_name == 'XY':
return PlaneEquation(0, 0, 1, 0)
elif plane_name == 'YZ':
return PlaneEquation(1, 0, 0, 0)
elif plane_name == 'XZ':
return PlaneEquation(0, 1, 0, 0)
else:
raise Exception("Unknown coordinate plane name")
@classmethod
def from_coordinate_value(cls, axis, value):
if axis in 'XYZ':
axis = 'XYZ'.index(axis)
elif axis not in {0, 1, 2}:
raise Exception("Unknown coordinate axis")
point = np.zeros((3,), dtype=np.float64)
normal = np.zeros((3,), dtype=np.float64)
point[axis] = value
normal[axis] = 1.0
return PlaneEquation.from_normal_and_point(normal, point)
@classmethod
def from_matrix(cls, matrix, normal_axis='Z'):
if normal_axis == 'X':
normal = Vector((1,0,0))
elif normal_axis == 'Y':
normal = Vector((0,1,0))
elif normal_axis == 'Z':
normal = Vector((0,0,1))
else:
raise Exception(f"Unsupported normal_axis = {normal_axis}; supported are: X,Y,Z")
normal = (matrix @ normal) - matrix.translation
point = matrix.translation
return PlaneEquation.from_normal_and_point(normal, point)
def normalized(self):
"""
Return equation, which defines exactly the same plane, but with coefficients adjusted so that
A^2 + B^2 + C^2 = 1
holds.
"""
normal = self.normal.length
if abs(normal) < 1e-8:
raise Exception("Normal of the plane is (nearly) zero: ({}, {}, {})".format(self.a, self.b, self.c))
return PlaneEquation(self.a/normal, self.b/normal, self.c/normal, self.d/normal)
def check(self, point, eps=1e-6):
"""
Check if specified point belongs to the plane.
"""
a, b, c, d = self.a, self.b, self.c, self.d
x, y, z = point[0], point[1], point[2]
value = a*x + b*y + c*z + d
return abs(value) < eps
def second_vector(self):
eps = 1e-6
if abs(self.c) > eps:
v = Vector((1, 0, -self.a/self.c))
elif abs(self.a) > eps:
v = Vector((-self.b/self.a, 1, 0))
elif abs(self.b) > eps:
v = Vector((1, -self.a/self.b, 0))
else:
raise Exception("plane normal is (almost) zero")
return v
def two_vectors(self, normalize=False):
"""
Return two vectors that are parallel two this plane.
Note: the two vectors returned are orthogonal.
Lengths of the returned vector is arbitrary.
output: (Vector, Vector)
"""
v1 = self.second_vector()
v2 = v1.cross(self.normal)
if normalize:
v1.normalize()
v2.normalize()
return v1, v2
def get_matrix(self, invert_y=False):
x = self.second_vector().normalized()
z = self.normal.normalized()
y = z.cross(x).normalized()
if invert_y:
y = - y
return Matrix([x, y, z]).transposed()
def point_uv_projection(self, point):
point = Vector(point) - self.nearest_point_to_origin()
matrix = self.get_matrix(invert_y=True).inverted()
uvw = matrix @ point
return uvw.xy
def evaluate(self, u, v, normalize=False):
"""
Return a point on the plane by it's UV coordinates.
UV coordinates origin is self.point.
Orientation of UV coordinates system is undefined.
Scale of UV coordinates system is defined by coordinates
of self.normal. One can use plane.normalized().evaluate()
to make sure that the scale of UV coordinates system is 1:1.
input: two floats.
output: Vector.
"""
p0 = self.nearest_point_to_origin()
v1, v2 = self.two_vectors(normalize)
return p0 + u*v1 + v*v2
@property
def normal(self):
return mathutils.Vector((self.a, self.b, self.c))
@normal.setter
def normal(self, normal):
self.a = normal[0]
self.b = normal[1]
self.c = normal[2]
def nearest_point_to_origin(self):
"""
Returns the point on plane which is the nearest
to the origin (0, 0, 0).
output: Vector.
"""
a, b, c, d = self.a, self.b, self.c, self.d
sqr = a*a + b*b + c*c
if sqr < 1e-8:
raise Exception("Plane normal is (almost) zero!")
return mathutils.Vector(((- a*d)/sqr, (- b*d)/sqr, (- c*d)/sqr))
def distance_to_point(self, point):
"""
Return distance from specified point to this plane.
input: Vector or 3-tuple
output: float.
"""
point_on_plane = self.nearest_point_to_origin()
return mathutils.geometry.distance_point_to_plane(mathutils.Vector(point), point_on_plane, self.normal)
def distance_to_points(self, points):
"""
Return distances from specified points to this plane.
input: list of 3-tuples, or numpy array of same shape
output: numpy array of floats.
"""
# Distance from (x,y,z) to the plane is given by formula:
#
# | A x + B y + C z + D |
# rho = -------------------------
# sqrt(A^2 + B^2 + C^2)
#
points = np.asarray(points)
a, b, c, d = self.a, self.b, self.c, self.d
# (A x + B y + C z) is a scalar product of (x, y, z) and (A, B, C)
numerators = abs(points.dot([a, b, c]) + d)
denominator = math.sqrt(a*a + b*b + c*c)
return numerators / denominator
def intersect_with_line(self, line, min_det=1e-12):
"""
Calculate intersection between this plane and specified line.
input: line - an instance of LineEquation.
output: Vector.
"""
a, b, c = line.a, line.b, line.c
x0, y0, z0 = line.x0, line.y0, line.z0
# Here we numerically solve the system of linear equations:
#
# / x - x0 y - y0 z - z0
# | ------ = ------ = ------, (line)
# / A B C (*)
# `
# | Ap x + Bp y + Cp z + Dp = 0 (plane)
# `
#
# with relation to x, y, z.
# It is possible that any two of A, B, C are equal to zero,
# but not all three of them.
# Depending on which of A, B, C is not zero, we should
# consider different representations of line equation.
#
# For example, if B != 0, we can represent (*) as
#
# B (x - x0) = A (y - y0),
# C (y - y0) = B (z - z0),
# Ap x + Bp x + Cp z + Dp = 0.
#
# But, if B == 0, then this representation will contain
# two exactly equivalent equations:
#
# 0 = A (y - y0),
# C (y - y0) = 0,
# Ap x + 0 + Cp z + Dp = 0.
#
# In this case, the system will become singular; so
# we must choose another representation of (*) system.
epsilon = 1e-8
#info("Line: %s", line)
if abs(a) > epsilon:
matrix = np.array([
[b, -a, 0],
[c, 0, -a],
[self.a, self.b, self.c]])
free = np.array([
b*x0 - a*y0,
c*x0 - a*z0,
-self.d])
elif abs(b) > epsilon:
matrix = np.array([
[b, -a, 0],
[0, c, -b],
[self.a, self.b, self.c]])
free = np.array([
b*x0 - a*y0,
c*y0 - b*z0,
-self.d])
elif abs(c) > epsilon:
matrix = np.array([
[c, 0, -a],
[0, c, -b],
[self.a, self.b, self.c]])
free = np.array([
c*x0 - a*z0,
c*y0 - b*z0,
-self.d])
else:
raise Exception("Invalid plane: all coefficients are (nearly) zero: {}, {}, {}".format(a, b, c))
det = linalg.det(matrix)
if abs(det) < min_det:
print(f"No intersection: det = {det}")
return None
#raise Exception("Plane: {}, line: {}, det: {}".format(self, line, det))