forked from 3BMLabs/building.py
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BuildingPy-revit.py
13616 lines (11409 loc) · 487 KB
/
BuildingPy-revit.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
#[BuildingPy] DO NOT EDIT THIS FILE. IT IS GENERATED FROM THE SOURCE CODE
import math
from math import sqrt, cos, sin, acos, degrees, radians, log, pi
import sys
import os
import re
import json
import bisect
from abc import *
from collections import defaultdict
from collections.abc import MutableSequence
import subprocess
import urllib
import time
import urllib.request
import string
import random
from typing import List, Tuple, Union
import xml.etree.ElementTree as ET
from pathlib import Path
import copy
import pickle
from functools import reduce
import struct
#import ezdxf
def find_in_list_of_list(mylist, char):
for sub_list in mylist:
if char in sub_list:
return (mylist.index(sub_list))
raise ValueError("'{char}' is not in list".format(char=char))
class generateID:
def __init__(self) -> None:
self.id = None
self.object = None
self.name = None
self.generateID()
def generateID(self) -> None:
id = ""
lengthID = 12
random_source = string.ascii_uppercase + string.digits
for x in range(lengthID):
id += random.choice(random_source)
id_list = list(id)
self.id = f"#"+"".join(id_list)
return f"test {self.__class__.__name__}"
def __repr__(self) -> str:
return f"{self.id}"
def findjson(id, json_string):
#faster way to search in json
results = []
def _decode_dict(a_dict):
try:
results.append(a_dict[id])
except KeyError:
pass
return a_dict
json.loads(json_string, object_hook=_decode_dict) # Return value ignored.
return results
def list_transpose(lst):
#list of lists, transpose columns/rows
newlist = list(map(list, zip(*lst)))
return newlist
def is_null(lst):
return all(el is None for el in lst)
def clean_list(input_list, preserve_indices=True):
if not input_list:
return input_list
culled_list = []
if preserve_indices:
if is_null(input_list):
return None
j = len(input_list) - 1
while j >= 0 and input_list[j] is None:
j -= 1
for i in range(j + 1):
sublist = input_list[i]
if isinstance(sublist, list):
val = clean_list(sublist, preserve_indices)
culled_list.append(val)
else:
culled_list.append(input_list[i])
else:
if is_null(input_list):
return []
for el in input_list:
if isinstance(el, list):
if not is_null(el):
val = clean_list(el, preserve_indices=False)
if val:
culled_list.append(val)
elif el is not None:
culled_list.append(el)
return culled_list
def flatten(lst):
if type(lst) != list:
lst = [lst]
flat_list = []
for sublist in lst:
try:
for item in sublist:
flat_list.append(item)
except:
flat_list.append(sublist)
return flat_list
def all_true(lst):
for element in lst:
if not element:
return False
return True
def replace_at_index(object, index, new_object):
if index < 0 or index >= len(object):
raise IndexError("Index out of range")
return object[:index] + new_object + object[index+1:]
def xmldata(myurl, xPathStrings):
urlFile = urllib.request.urlopen(myurl)
tree = ET.parse(urlFile)
xPathResults = []
for xPathString in xPathStrings:
a = tree.findall(xPathString)
xPathResulttemp2 = []
for xPathResult in a:
xPathResulttemp2.append(xPathResult.text)
xPathResults.append(xPathResulttemp2)
return xPathResults
COMMANDS = set("MmZzLlHhVvCcSsQqTtAa")
UPPERCASE = set("MZLHVCSQTA")
COMMAND_RE = re.compile(r"([MmZzLlHhVvCcSsQqTtAa])")
FLOAT_RE = re.compile(rb"^[-+]?\d*\.?\d*(?:[eE][-+]?\d+)?")
class InvalidPathError(ValueError):
pass
# The argument sequences from the grammar, made sane.
# u: Non-negative number
# s: Signed number or coordinate
# c: coordinate-pair, which is two coordinates/numbers, separated by whitespace
# f: A one character flag, doesn't need whitespace, 1 or 0
ARGUMENT_SEQUENCE = {
"M": "c",
"Z": "",
"L": "c",
"H": "s",
"V": "s",
"C": "ccc",
"S": "cc",
"Q": "cc",
"T": "c",
"A": "uusffc",
}
def strip_array(arg_array):
"""Strips whitespace and commas"""
# EBNF wsp:(#x20 | #x9 | #xD | #xA) + comma: 0x2C
while arg_array and arg_array[0] in (0x20, 0x9, 0xD, 0xA, 0x2C):
arg_array[0:1] = b""
def pop_number(arg_array):
res = FLOAT_RE.search(arg_array)
if not res or not res.group():
raise InvalidPathError(f"Expected a number, got '{arg_array}'.")
number = float(res.group())
start = res.start()
end = res.end()
arg_array[start:end] = b""
strip_array(arg_array)
return number
def pop_unsigned_number(arg_array):
number = pop_number(arg_array)
if number < 0:
raise InvalidPathError(f"Expected a non-negative number, got '{number}'.")
return number
def pop_coordinate_pair(arg_array):
x = pop_number(arg_array)
y = pop_number(arg_array)
return complex(x, y)
def pop_flag(arg_array):
flag = arg_array[0]
arg_array[0:1] = b""
strip_array(arg_array)
if flag == 48: # ASCII 0
return False
if flag == 49: # ASCII 1
return True
FIELD_POPPERS = {
"u": pop_unsigned_number,
"s": pop_number,
"c": pop_coordinate_pair,
"f": pop_flag,
}
def _commandify_path(pathdef):
"""Splits path into commands and arguments"""
token = None
for x in COMMAND_RE.split(pathdef):
x = x.strip()
if x in COMMANDS:
if token is not None:
yield token
if x in ("z", "Z"):
# The end command takes no arguments, so add a blank one
token = (x, "")
else:
token = (x,)
elif x:
if token is None:
raise InvalidPathError(f"Path does not start with a command: {pathdef}")
token += (x,)
yield token
def _tokenize_path(pathdef):
for command, args in _commandify_path(pathdef):
# Shortcut this for the close command, that doesn't have arguments:
if command in ("z", "Z"):
yield (command,)
continue
# For the rest of the commands, we parse the arguments and
# yield one command per full set of arguments
arg_sequence = ARGUMENT_SEQUENCE[command.upper()]
arguments = bytearray(args, "ascii")
implicit = False
while arguments:
command_arguments = []
for i, arg in enumerate(arg_sequence):
try:
command_arguments.append(FIELD_POPPERS[arg](arguments))
except InvalidPathError as e:
if i == 0 and implicit:
return # Invalid character in path, treat like a comment
raise InvalidPathError(
f"Invalid path element {command} {args}"
) from e
yield (command,) + tuple(command_arguments)
implicit = True
# Implicit Moveto commands should be treated as Lineto commands.
if command == "m":
command = "l"
elif command == "M":
command = "L"
def parse_path(pathdef):
segments = Path()
start_pos = None
last_command = None
current_pos = 0
for token in _tokenize_path(pathdef):
command = token[0]
relative = command.islower()
command = command.upper()
if command == "M":
pos = token[1]
if relative:
current_pos += pos
else:
current_pos = pos
segments.append(Move(current_pos, relative=relative))
start_pos = current_pos
elif command == "Z":
# For Close commands the "relative" argument just preserves case,
# it has no different in behavior.
segments.append(Close(current_pos, start_pos, relative=relative))
current_pos = start_pos
elif command == "L":
pos = token[1]
if relative:
pos += current_pos
segments.append(Line(current_pos, pos, relative=relative))
current_pos = pos
elif command == "H":
hpos = token[1]
if relative:
hpos += current_pos.real
pos = complex(hpos, current_pos.imag)
segments.append(
Line(current_pos, pos, relative=relative, horizontal=True)
)
current_pos = pos
elif command == "V":
vpos = token[1]
if relative:
vpos += current_pos.imag
pos = complex(current_pos.real, vpos)
segments.append(
Line(current_pos, pos, relative=relative, vertical=True)
)
current_pos = pos
elif command == "C":
control1 = token[1]
control2 = token[2]
end = token[3]
if relative:
control1 += current_pos
control2 += current_pos
end += current_pos
segments.append(
CubicBezier(
current_pos, control1, control2, end, relative=relative
)
)
current_pos = end
elif command == "S":
# Smooth curve. First control point is the "reflection" of
# the second control point in the previous
control2 = token[1]
end = token[2]
if relative:
control2 += current_pos
end += current_pos
if last_command in "CS":
# The first control point is assumed to be the reflection of
# the second control point on the previous command relative
# to the current point.
control1 = current_pos + current_pos - segments[-1].control2
else:
# If there is no previous command or if the previous command
# was not an C, c, S or s, assume the first control point is
# coincident with the current point.
control1 = current_pos
segments.append(
CubicBezier(
current_pos, control1, control2, end, relative=relative, smooth=True
)
)
current_pos = end
elif command == "Q":
control = token[1]
end = token[2]
if relative:
control += current_pos
end += current_pos
segments.append(
QuadraticBezier(current_pos, control, end, relative=relative)
)
current_pos = end
elif command == "T":
# Smooth curve. Control point is the "reflection" of
# the second control point in the previous
end = token[1]
if relative:
end += current_pos
if last_command in "QT":
# The control point is assumed to be the reflection of
# the control point on the previous command relative
# to the current point.
control = current_pos + current_pos - segments[-1].control
else:
# If there is no previous command or if the previous command
# was not an Q, q, T or t, assume the first control point is
# coincident with the current point.
control = current_pos
segments.append(
QuadraticBezier(
current_pos, control, end, smooth=True, relative=relative
)
)
current_pos = end
elif command == "A":
# For some reason I implemented the Arc with a complex radius.
# That doesn't really make much sense, but... *shrugs*
radius = complex(token[1], token[2])
rotation = token[3]
arc = token[4]
sweep = token[5]
end = token[6]
if relative:
end += current_pos
segments.append(
Arc(
current_pos, radius, rotation, arc, sweep, end, relative=relative
)
)
current_pos = end
# Finish up the loop in preparation for next command
last_command = command
return segments
MIN_DEPTH = 5
ERROR = 1e-12
def segment_length(curve, start, end, start_point, end_point, error, min_depth, depth):
"""Recursively approximates the length by straight lines"""
mid = (start + end) / 2
mid_point = curve.point(mid)
length = abs(end_point - start_point)
first_half = abs(mid_point - start_point)
second_half = abs(end_point - mid_point)
length2 = first_half + second_half
if (length2 - length > error) or (depth < min_depth):
# Calculate the length of each segment:
depth += 1
return segment_length(
curve, start, mid, start_point, mid_point, error, min_depth, depth
) + segment_length(
curve, mid, end, mid_point, end_point, error, min_depth, depth
)
# This is accurate enough.
return length2
class PathSegment(ABC):
@abstractmethod
def point(self, pos):
"""Returns the coordinate point (as a complex number) of a point on the path,
as expressed as a floating point number between 0 (start) and 1 (end).
"""
@abstractmethod
def tangent(self, pos):
"""Returns a vector (as a complex number) representing the tangent of a point
on the path as expressed as a floating point number between 0 (start) and 1 (end).
"""
@abstractmethod
def length(self, error=ERROR, min_depth=MIN_DEPTH):
"""Returns the length of a path.
The CubicBezier and Arc lengths are non-exact and iterative and you can select to
either do the calculations until a maximum error has been achieved, or a minimum
number of iterations.
"""
class NonLinear(PathSegment):
"""A line that is not straight
The base of Arc, QuadraticBezier and CubicBezier
"""
class Linear(PathSegment):
"""A straight line
The base for Line() and Close().
"""
def __init__(self, start, end, relative=False):
self.start = start
self.end = end
self.relative = relative
def __ne__(self, other):
if not isinstance(other, Line):
return NotImplemented
return not self == other
def point(self, pos):
distance = self.end - self.start
return self.start + distance * pos
def tangent(self, pos):
return self.end - self.start
def length(self, error=None, min_depth=None):
distance = self.end - self.start
return sqrt(distance.real**2 + distance.imag**2)
class Line(Linear):
def __init__(self, start, end, relative=False, vertical=False, horizontal=False):
self.start = start
self.end = end
self.relative = relative
self.vertical = vertical
self.horizontal = horizontal
def __repr__(self):
return f"Line(start={self.start}, end={self.end})"
def __eq__(self, other):
if not isinstance(other, Line):
return NotImplemented
return self.start == other.start and self.end == other.end
def _d(self, previous):
x = self.end.real
y = self.end.imag
if self.relative:
x -= previous.end.real
y -= previous.end.imag
if self.horizontal and self.is_horizontal_from(previous):
cmd = "h" if self.relative else "H"
return f"{cmd} {x:G},{y:G}"
if self.vertical and self.is_vertical_from(previous):
cmd = "v" if self.relative else "V"
return f"{cmd} {y:G}"
cmd = "l" if self.relative else "L"
return f"{cmd} {x:G},{y:G}"
def is_vertical_from(self, previous):
return self.start == previous.end and self.start.real == self.end.real
def is_horizontal_from(self, previous):
return self.start == previous.end and self.start.imag == self.end.imag
class CubicBezier(NonLinear):
def __init__(self, start, control1, control2, end, relative=False, smooth=False):
self.start = start
self.control1 = control1
self.control2 = control2
self.end = end
self.relative = relative
self.smooth = smooth
def __repr__(self):
return (
f"CubicBezier(start={self.start}, control1={self.control1}, "
f"control2={self.control2}, end={self.end}, smooth={self.smooth})"
)
def __eq__(self, other):
if not isinstance(other, CubicBezier):
return NotImplemented
return (
self.start == other.start
and self.end == other.end
and self.control1 == other.control1
and self.control2 == other.control2
)
def __ne__(self, other):
if not isinstance(other, CubicBezier):
return NotImplemented
return not self == other
def _d(self, previous):
c1 = self.control1
c2 = self.control2
end = self.end
if self.relative and previous:
c1 -= previous.end
c2 -= previous.end
end -= previous.end
if self.smooth and self.is_smooth_from(previous):
cmd = "s" if self.relative else "S"
return f"{cmd} {c2.real:G},{c2.imag:G} {end.real:G},{end.imag:G}"
cmd = "c" if self.relative else "C"
return f"{cmd} {c1.real:G},{c1.imag:G} {c2.real:G},{c2.imag:G} {end.real:G},{end.imag:G}"
def is_smooth_from(self, previous):
"""Checks if this segment would be a smooth segment following the previous"""
if isinstance(previous, CubicBezier):
return self.start == previous.end and (self.control1 - self.start) == (
previous.end - previous.control2
)
else:
return self.control1 == self.start
def set_smooth_from(self, previous):
assert isinstance(previous, CubicBezier)
self.start = previous.end
self.control1 = previous.end - previous.control2 + self.start
self.smooth = True
def point(self, pos):
"""Calculate the x,y position at a certain position of the path"""
return (
((1 - pos) ** 3 * self.start)
+ (3 * (1 - pos) ** 2 * pos * self.control1)
+ (3 * (1 - pos) * pos**2 * self.control2)
+ (pos**3 * self.end)
)
def tangent(self, pos):
return (
-3 * (1 - pos) ** 2 * self.start
+ 3 * (1 - pos) ** 2 * self.control1
- 6 * pos * (1 - pos) * self.control1
- 3 * pos**2 * self.control2
+ 6 * pos * (1 - pos) * self.control2
+ 3 * pos**2 * self.end
)
def length(self, error=ERROR, min_depth=MIN_DEPTH):
"""Calculate the length of the path up to a certain position"""
start_point = self.point(0)
end_point = self.point(1)
return segment_length(self, 0, 1, start_point, end_point, error, min_depth, 0)
class QuadraticBezier(NonLinear):
def __init__(self, start, control, end, relative=False, smooth=False):
self.start = start
self.end = end
self.control = control
self.relative = relative
self.smooth = smooth
def __repr__(self):
return (
f"QuadraticBezier(start={self.start}, control={self.control}, "
f"end={self.end}, smooth={self.smooth})"
)
def __eq__(self, other):
if not isinstance(other, QuadraticBezier):
return NotImplemented
return (
self.start == other.start
and self.end == other.end
and self.control == other.control
)
def __ne__(self, other):
if not isinstance(other, QuadraticBezier):
return NotImplemented
return not self == other
def _d(self, previous):
control = self.control
end = self.end
if self.relative and previous:
control -= previous.end
end -= previous.end
if self.smooth and self.is_smooth_from(previous):
cmd = "t" if self.relative else "T"
return f"{cmd} {end.real:G},{end.imag:G}"
cmd = "q" if self.relative else "Q"
return f"{cmd} {control.real:G},{control.imag:G} {end.real:G},{end.imag:G}"
def is_smooth_from(self, previous):
"""Checks if this segment would be a smooth segment following the previous"""
if isinstance(previous, QuadraticBezier):
return self.start == previous.end and (self.control - self.start) == (
previous.end - previous.control
)
else:
return self.control == self.start
def set_smooth_from(self, previous):
assert isinstance(previous, QuadraticBezier)
self.start = previous.end
self.control = previous.end - previous.control + self.start
self.smooth = True
def point(self, pos):
return (
(1 - pos) ** 2 * self.start
+ 2 * (1 - pos) * pos * self.control
+ pos**2 * self.end
)
def tangent(self, pos):
return (
self.start * (2 * pos - 2)
+ (2 * self.end - 4 * self.control) * pos
+ 2 * self.control
)
def length(self, error=None, min_depth=None):
a = self.start - 2 * self.control + self.end
b = 2 * (self.control - self.start)
try:
# For an explanation of this case, see
# http://www.malczak.info/blog/quadratic-bezier-curve-length/
A = 4 * (a.real**2 + a.imag**2)
B = 4 * (a.real * b.real + a.imag * b.imag)
C = b.real**2 + b.imag**2
Sabc = 2 * sqrt(A + B + C)
A2 = sqrt(A)
A32 = 2 * A * A2
C2 = 2 * sqrt(C)
BA = B / A2
s = (
A32 * Sabc
+ A2 * B * (Sabc - C2)
+ (4 * C * A - B**2) * log((2 * A2 + BA + Sabc) / (BA + C2))
) / (4 * A32)
except (ZeroDivisionError, ValueError):
if abs(a) < 1e-10:
s = abs(b)
else:
k = abs(b) / abs(a)
if k >= 2:
s = abs(b) - abs(a)
else:
s = abs(a) * (k**2 / 2 - k + 1)
return s
class Arc(NonLinear):
def __init__(self, start, radius, rotation, arc, sweep, end, relative=False):
"""radius is complex, rotation is in degrees,
large and sweep are 1 or 0 (True/False also work)"""
self.start = start
self.radius = radius
self.rotation = rotation
self.arc = bool(arc)
self.sweep = bool(sweep)
self.end = end
self.relative = relative
self._parameterize()
def __repr__(self):
return (
f"Arc(start={self.start}, radius={self.radius}, rotation={self.rotation}, "
f"arc={self.arc}, sweep={self.sweep}, end={self.end})"
)
def __eq__(self, other):
if not isinstance(other, Arc):
return NotImplemented
return (
self.start == other.start
and self.end == other.end
and self.radius == other.radius
and self.rotation == other.rotation
and self.arc == other.arc
and self.sweep == other.sweep
)
def __ne__(self, other):
if not isinstance(other, Arc):
return NotImplemented
return not self == other
def _d(self, previous):
end = self.end
cmd = "a" if self.relative else "A"
if self.relative:
end -= previous.end
return (
f"{cmd} {self.radius.real:G},{self.radius.imag:G} {self.rotation:G} "
f"{int(self.arc):d},{int(self.sweep):d} {end.real:G},{end.imag:G}"
)
def _parameterize(self):
# Conversion from endpoint to center parameterization
# http://www.w3.org/TR/SVG/implnote.html#ArcImplementationNotes
if self.start == self.end:
# This is equivalent of omitting the segment, so do nothing
return
if self.radius.real == 0 or self.radius.imag == 0:
# This should be treated as a straight line
return
cosr = cos(radians(self.rotation))
sinr = sin(radians(self.rotation))
dx = (self.start.real - self.end.real) / 2
dy = (self.start.imag - self.end.imag) / 2
x1prim = cosr * dx + sinr * dy
x1prim_sq = x1prim * x1prim
y1prim = -sinr * dx + cosr * dy
y1prim_sq = y1prim * y1prim
rx = self.radius.real
rx_sq = rx * rx
ry = self.radius.imag
ry_sq = ry * ry
# Correct out of range radii
radius_scale = (x1prim_sq / rx_sq) + (y1prim_sq / ry_sq)
if radius_scale > 1:
radius_scale = sqrt(radius_scale)
rx *= radius_scale
ry *= radius_scale
rx_sq = rx * rx
ry_sq = ry * ry
self.radius_scale = radius_scale
else:
# SVG spec only scales UP
self.radius_scale = 1
t1 = rx_sq * y1prim_sq
t2 = ry_sq * x1prim_sq
c = sqrt(abs((rx_sq * ry_sq - t1 - t2) / (t1 + t2)))
if self.arc == self.sweep:
c = -c
cxprim = c * rx * y1prim / ry
cyprim = -c * ry * x1prim / rx
self.center = complex(
(cosr * cxprim - sinr * cyprim) + ((self.start.real + self.end.real) / 2),
(sinr * cxprim + cosr * cyprim) + ((self.start.imag + self.end.imag) / 2),
)
ux = (x1prim - cxprim) / rx
uy = (y1prim - cyprim) / ry
vx = (-x1prim - cxprim) / rx
vy = (-y1prim - cyprim) / ry
n = sqrt(ux * ux + uy * uy)
p = ux
theta = degrees(acos(p / n))
if uy < 0:
theta = -theta
self.theta = theta % 360
n = sqrt((ux * ux + uy * uy) * (vx * vx + vy * vy))
p = ux * vx + uy * vy
d = p / n
# In certain cases the above calculation can through inaccuracies
# become just slightly out of range, f ex -1.0000000000000002.
if d > 1.0:
d = 1.0
elif d < -1.0:
d = -1.0
delta = degrees(acos(d))
if (ux * vy - uy * vx) < 0:
delta = -delta
self.delta = delta % 360
if not self.sweep:
self.delta -= 360
def point(self, pos):
if self.start == self.end:
# This is equivalent of omitting the segment
return self.start
if self.radius.real == 0 or self.radius.imag == 0:
# This should be treated as a straight line
distance = self.end - self.start
return self.start + distance * pos
angle = radians(self.theta + (self.delta * pos))
cosr = cos(radians(self.rotation))
sinr = sin(radians(self.rotation))
radius = self.radius * self.radius_scale
x = (
cosr * cos(angle) * radius.real
- sinr * sin(angle) * radius.imag
+ self.center.real
)
y = (
sinr * cos(angle) * radius.real
+ cosr * sin(angle) * radius.imag
+ self.center.imag
)
return complex(x, y)
def tangent(self, pos):
angle = radians(self.theta + (self.delta * pos))
cosr = cos(radians(self.rotation))
sinr = sin(radians(self.rotation))
radius = self.radius * self.radius_scale
x = cosr * cos(angle) * radius.real - sinr * sin(angle) * radius.imag
y = sinr * cos(angle) * radius.real + cosr * sin(angle) * radius.imag
return complex(x, y) * complex(0, 1)
def length(self, error=ERROR, min_depth=MIN_DEPTH):
"""The length of an elliptical arc segment requires numerical
integration, and in that case it's simpler to just do a geometric
approximation, as for cubic bezier curves.
"""
if self.start == self.end:
# This is equivalent of omitting the segment
return 0
if self.radius.real == 0 or self.radius.imag == 0:
# This should be treated as a straight line
distance = self.end - self.start
return sqrt(distance.real**2 + distance.imag**2)
if self.radius.real == self.radius.imag:
# It's a circle, which simplifies this a LOT.
radius = self.radius.real * self.radius_scale
return abs(radius * self.delta * pi / 180)
start_point = self.point(0)
end_point = self.point(1)
return segment_length(self, 0, 1, start_point, end_point, error, min_depth, 0)
class Move:
"""Represents move commands. Does nothing, but is there to handle
paths that consist of only move commands, which is valid, but pointless.
"""
def __init__(self, to, relative=False):
self.start = self.end = to
self.relative = relative
def __repr__(self):
return "Move(to=%s)" % self.start
def __eq__(self, other):
if not isinstance(other, Move):
return NotImplemented
return self.start == other.start
def __ne__(self, other):
if not isinstance(other, Move):
return NotImplemented
return not self == other
def _d(self, previous):
cmd = "M"
x = self.end.real
y = self.end.imag
if self.relative:
cmd = "m"
if previous:
x -= previous.end.real
y -= previous.end.imag
return f"{cmd} {x:G},{y:G}"
def point(self, pos):
return self.start
def tangent(self, pos):
return 0
def length(self, error=ERROR, min_depth=MIN_DEPTH):
return 0
class Close(Linear):